我有这样的东西
@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。
问题在于,在这种情况下,注入不起作用,并且testController中的testService为null。
是否可以提供注入静态对象的功能(在Controller中无需创建构造函数)?
也许对此还有另一种解决方法?
问题不是关于模拟静态方法,而是关于将模拟注入静态对象
将不胜感激任何意见,谢谢。
最佳答案
我认为您将必须使用static
块。
@RunWith(MockitoJUnitRunner.class)
public class TestControllerTest {
private static TestService testService = mock(TestService.class);
private static TestController testController ;
static {
testController = new TestController(testService);
}
....
}
使用魔术注入时,必须使用一些反射,或更改为构造函数注入。无论如何,生活会更好。