【发布时间】:2020-03-25 09:48:42
【问题描述】:
我有以下用例:
我有一个包含 3 个组件的测试类,其中 2 个被注入到第三个中;我正在使用 JUnit 和 Mockito 进行测试
public class MyTestClass{
@Mock
SomeService someService;
@Mock
AnotherService anotherService;
@InjectMock
MainService mainService;
@BeforeMethod
public void init() {
initMocks(this);
}
@Test
public void test(){
when(someService.someMethod(any())).thenReturn(something);
when(anotherService.someMethod(any()).thenReturn(something);
mainService.someMainMerhod();
// ...other assert logic
}
}
这里我有注入其他两个组件的 MainService Spring 组件
@Component
public class MainService{
@Autowired
private SomeService someService; //Why here I have null component
private AnotherService anotherService; // and here I have an initialized component ???
public MainService(AnotherService anotherService){
this.anotherService = anotherService;
}
// implementation
}
问题 1:为什么我同时使用构造函数和 @Autowired 时 someService 实例为空?
问题 2:为什么如果我只使用没有 @Autowired 的构造函数,反之亦然,一切正常,因为我不加载 Spring 上下文...我有单元测试...
【问题讨论】:
标签: java spring unit-testing junit mocking