自动插入其余依赖项时,@ InjectMocks不起作用

Dag*_*ago 1 junit spring mocking mockito autowired

我正在尝试ClassA使用2服务的测试。一种服务需要自动连线,而另一种则被视为模拟对象。不幸的是,嘲笑的对象是

没有注射

参加我的测试班。所有字段的行为都像我只会使用spring自动装配功能来进行设置一样。经过测试的ClassA也从其他抽象类继承。如果不使用自动装配,则模拟对象将成功传递。不幸的是,我无法嘲笑ServiceDao,这就是为什么我尝试合并 @InjectMocks@Autowiring注释的原因。

A级

public ClassA extends AbstractClassA<ClassOne, ClassTwo>{

   @Autowired
   protected ServiceOne serviceOne;      //this services needs to be mocked

   @Override
   protected List<ClassTwo> testedMethod(){
      return serviceOne.getList();      //here method is not returning mocked objects 
   }                                    //as it supposed to do.
     ........
}
Run Code Online (Sandbox Code Playgroud)

抽象类

public class AbstractClassA<T1 extends InterfaceOne, T2 extends InterfaceTwo){
    @Autowired
    protected ServiceDAO serviceDAO; //this services needs to be autowired

    protected abstract List<T2> testedMethod();

}
Run Code Online (Sandbox Code Playgroud)

TestClass。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:testApplicationContext.xml"})
public class Test {
    @Mock
    private ServiceOne serviceOne; //this mock object and it's return
                                   //objects are set properly


    @Autowired
    @InjectMocks
    private ClassA classA;  //all fields are autowired, including the services that should be mocked

    @Before
    public void setData(){
       Mockito.Annotations.initMocks(this);
       List<ClassTwo> result = Arrays.asList(new ClassA());
       when(serviceOne.testedMethod().thenReturn(result); //here when i invoke mocked object it is returning correct list.  
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

在这种情况下,最好是通过Spring测试上下文配置来模拟注入的bean。如果您不能轻松做到这一点,则可以使用Springs ReflectionTestUtils类来模拟服务中的单个对象。

在测试配置XML文件中,您可以定义一个模拟bean:

<bean id="serviceOne" class="org.mockito.Mockito" factory-method="mock"/>
    <constructor-arg value="com.package.ServiceOne"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

在Java方面:

@Bean
public ServiceOne serviceOne() {
    return mock(ServiceOne.class);
}
Run Code Online (Sandbox Code Playgroud)

在测试用例中,您可以@Autowire ServiceOne serviceOne并将其用作模拟对象:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:testApplicationContext.xml"})
public class Test {
    @Autowired
    private ServiceOne serviceOne; 

    @Autowired
    private ClassA classA; 

    @Before
    public void setData(){
       Mockito.Annotations.initMocks(this);
       List<ClassTwo> result = Arrays.asList(new ClassA());
       when(serviceOne.testedMethod()).thenReturn(result);
  }
}
Run Code Online (Sandbox Code Playgroud)