我有这样的东西
@Component
public class TestController {
@Autowired
private TestService testService;
public String getSomething(String parameter1) {
return testService.fetchSomething(parameter1);
}
}
我正在用测试覆盖它并遇到以下问题:
@RunWith(MockitoJUnitRunner.class)
public class TestControllerTest {
private static TestService testService = mock(TestService.class);
@InjectMocks
private static TestController testController = new TestController();
....
}
这些字段是静态的,因为我需要它们用于 @ClassRule。
问题是在这种情况下注入(inject)不起作用,并且 testService 在 testController 中为 null。
是否可以提供对静态对象的注入(inject)(无需在 Controller 中创建构造函数)? 或者也许还有另一种解决方法?
问题不在于模拟静态方法,而是将模拟注入(inject)静态对象 非常感谢任何建议,谢谢。
最佳答案
我认为你必须使用static
block 。
@RunWith(MockitoJUnitRunner.class)
public class TestControllerTest {
private static TestService testService = mock(TestService.class);
private static TestController testController ;
static {
testController = new TestController(testService);
}
....
}
当你使用神奇的注入(inject)时,你必须使用一些反射,或者更改为构造函数注入(inject)。无论如何,生活会更好。
关于java - Mockito 将Mocks注入(inject)静态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33755789/