【问题标题】:Mock JmsTemplate for integration testing用于集成测试的模拟 JmsTemplate
【发布时间】:2014-08-07 09:08:28
【问题描述】:

需要模拟 JmsTemplate 以在我的应用程序中进行集成测试。

在我的 appcontext.xml 中

<bean id="core_connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiTemplate">
            <ref bean="core_jndiTemplate" />
        </property>
        <property name="jndiName">
            <value>ConnectionFactory</value>
        </property>
    </bean>

    <bean id="core_jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="core_connectionFactory" />
        <property name="defaultDestination" ref="core_destination" />
    </bean>


    <bean id="core_destination" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiTemplate">
            <ref bean="core_jndiTemplate" />
        </property>
        <property name="jndiName">
            <value>queue/CoreQueue</value>
        </property>
    </bean>

需要在我的 testcontext.xml 中模拟 jmstemplete。 提前致谢。

【问题讨论】:

  • core_jmsTemplate 不在任何地方使用 - 对吗?我认为没有必要嘲笑。不过,您可以使用 Spring 配置文件来根据活动配置文件创建一个或另一个 bean。
  • 我在 test-context.xml 中导入 app-context.xml,所以需要初始化。

标签: java spring spring-jms springmockito


【解决方案1】:

或者在 Spring 4 中 ;)

@Bean
public JmsTemplate jmsTemplate() {
    return Mockito.mock(JmsTemplate.class);
}

正如@Stephane 所说,但没有 xml。
但我仍然建议您使用嵌入式代理进行集成测试。因为它可以让您检查队列中到底有什么。

【讨论】:

    【解决方案2】:

    下面的呢?

    <bean id="core_jmsTemplate" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="org.springframework.jms.core.JmsTemplate"/>
    </bean>
    

    您可能需要在测试中注入模板并配置模拟 (given(...).willReturn)。

    【讨论】:

    • 我有一个问题,即 Spring 创建一个模拟代理,就像它是一个普通的 bean。在这种情况下when(..).thenReturn(..) 工作正常,但verify(..) 说我应该在模拟上执行该方法。
    • 没有理由在那个东西上创建一个代理,除非你的应用中有一个超宽切入点的方面。恐怕您需要弄清楚创建代理的原因。
    猜你喜欢
    • 1970-01-01
    • 2022-07-12
    • 2012-04-25
    • 2011-03-15
    • 2022-08-11
    • 2017-01-23
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    相关资源
    最近更新 更多