@ injectmock在自动装配其余依赖项时不起作用



我正在尝试测试使用2个服务的ClassA。一个服务需要自动连接,另一个需要作为模拟对象处理。不幸的是,模拟对象是

不注射

到我测试的类。所有字段的行为就像我只使用spring自动装配功能来设置它一样。被测试的类a也从其他抽象类继承。如果没有使用自动装配,则模拟对象被成功传递。不幸的是,我不能嘲笑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.
     ........
}

AbstractClass

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

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.  
  }
}

在这种情况下,最好通过Spring测试上下文配置模拟注入的bean。如果你不能很容易地做到这一点,你可以使用spring的reflectiontesttils类来模拟服务中的单个对象。

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

<bean id="serviceOne" class="org.mockito.Mockito" factory-method="mock"/>
    <constructor-arg value="com.package.ServiceOne"/>
</bean>

Java端:

@Bean
public ServiceOne serviceOne() {
    return mock(ServiceOne.class);
}

在您的测试用例中,您可以@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);
  }
}

相关内容

  • 没有找到相关文章

最新更新