如何在测试期间模拟弹簧组件而不从中提取界面?

时间:2016-02-18 07:47:11

标签: java spring unit-testing interface mockito

有一个带有@Component注释的spring组件,它只是带有带注释的@Autowired字段的java类(不是接口)。我试图创建这样的模拟:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
    >
  <bean id="myComponent" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.MyComponent"/>
  </bean>
</beans>

有一个例外,一些字段没有自动装配。发生这种情况,因为当Spring看到<constructor-arg value="com.MyComponent"/>时,它会尝试实例化MyComponent bean并将其传递给工厂方法。

我试图从组件中提取接口,在这种情况下,模拟工作,但有没有办法让它工作而不提取接口?

同时

我尝试添加type="java.lang.Class",但遇到了同样的错误。

  <bean id="myComponent" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg  type="java.lang.Class"  value="com.MyComponent"/>
  </bean>

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

Spring无法自动装配bean,因为创建的bean的类型是Private Sub Dir1_Change() On Error Resume Next File1.Path = Dir1.Path If Err.Number = 0 Then Exit Sub Select Case Err.Number Case 68 Msgbox ("Device not ready") Case Else MsgBox ("Error " & Err.NUmber) '# Modify as needed... End Select End Sub Private Sub Drive1_Change() On Error Resume Next Dir1.Path = Drive1.Drive If Err.Number = 0 Then Exit Sub Select Case Err.Number Case 68 Msgbox ("Device not ready") Case Else MsgBox ("Error " & Err.NUmber) '# Modify as needed... End Select End Sub 而不是java.lang.Object。显然,XML中定义的顺序也很重要。

Jayway有一篇非常好的博客文章:Spring Integration Tests - Creating Mock Objects

您可以创建一个com.myComponent,返回正确的类:

FactoryBean

使用此工厂bean,您可以创建如下配置:

public class MockitoFactoryBean<T> implements FactoryBean<T> {

    private Class<T> classToBeMocked;

    /**
     * Creates a Mockito mock instance of the provided class.
     * @param classToBeMocked The class to be mocked.
     */
    public MockitoFactoryBean(Class<T> classToBeMocked) {
        this.classToBeMocked = classToBeMocked;
    }

    @Override
    public T getObject() throws Exception {
        return Mockito.mock(classToBeMocked);
    }

    @Override
    public Class<?> getObjectType() {
        return classToBeMocked;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

这将模拟您的组件,对象类型将<bean id="myComponent" class="com.yourpackage.MockitoFactoryBean"> <constructor-arg name="classToBeMocked" value="com.myComponent" /> </bean>

更新

这是原始答案和解释(使用EasyMock):Autowiring of beans generated by EasyMock factory-method?