【问题标题】:Unit Test - Null mocked component is injected单元测试 - 注入 Null 模拟组件
【发布时间】: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


    【解决方案1】:

    Javadoc 声明: “Mockito 将尝试仅通过构造函数注入、setter 注入或属性注入的顺序注入模拟。如果任何策略失败,则 Mockito 不会报告失败;即您必须自己提供依赖项。”

    因此它会默默地失败。

    【讨论】:

    • 在这种情况下,它只会尝试使用构造函数并忽略其他方法,如字段注入?
    • 是的,@InjectMocks 注释仅将模拟注入构造函数,而未定义字段。您可以在下面尝试测试是否正确
    • @Before public void setUp() throws Exception { anotherService = mock(AnotherService.class); obj = new MainService(anotherService); MockitoAnnotations.initMocks(this); }
    猜你喜欢
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2021-04-05
    相关资源
    最近更新 更多