单元测试-注入了空的模拟组件

时间:2020-03-25 09:48:42

标签: java spring unit-testing junit mocking

我有以下用例:

我有一个包含3个组件的Test类,其中有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实例为null?

问题2 :为什么如果我仅使用不带@Autowired的构造函数,反之亦然,那么一切正常,因为我没有加载Spring上下文...我有单元测试... < / p>

1 个答案:

答案 0 :(得分:1)

Javadoc指出: “ Mockito将尝试按顺序仅通过构造函数注入,setter注入或属性注入来注入模拟。如果任何策略失败,则Mockito不会报告失败;也就是说,您必须自己提供依赖项。”

因此它将无声地失败。