【发布时间】:2019-08-01 07:46:26
【问题描述】:
我有配置类:
@ConfigurationProperties(prefix = "myConfig")
public class MyConfig {
protected String config;
}
我的服务使用这个配置类(从application.yml获取值):
@Service
public class myService {
@Inject
private MyConfig myConfig;
Public String getInfo (String param) {
if (isEmpty(param)) { throw new InvalidParameterException; }
return myConfig.getConfig();
}
}
我正在尝试使用 Mockito 对其进行测试:
@RunWith(MockitoJUnitRunner.class)
public class myTest {
@InjectMocks
private MyService myService;
@Mock
private MyConfig myConfig;
@Test
public void myTest1() {
myService.getInfo("a");
}
@Test
public void myTest2() {
assertThrows(InvalidParameterException.class, ()->myService.getInfo(null));
}
}
myTest 失败,因为配置类被模拟,因此具有空值。
使用 Mockito 测试配置类的正确方法是什么?
编辑:
我有许多配置类,例如上面的配置类,它们在 myService 中使用。
【问题讨论】:
-
您必须定义
myConfig模拟的行为。例如:when(myConfig.getConfig()).thenReturn( ... );其中...是您想要返回的任何内容。但是,如果要定义行为,则需要 MyConfig 对象中的方法。您可能还想在您的问题中添加一些代码,以便我们可以看到MyService实际在做什么。 -
你可能想看看这个问题:stackoverflow.com/questions/31745168/…