【问题标题】:How to mock JmsTemplate with Mockito?如何用 Mockito 模拟 JmsTemplate?
【发布时间】:2018-10-08 08:22:42
【问题描述】:

我尝试测试一个发送 jms 消息但我无法模拟 JmsTemplate 的类

JmsProducer.class :

@Component
public class JmsProducer {

@Autowired
private JmsTemplate jmsTemplate;

@Value("${destination}")
private String destination;

public void send(String message){
    jmsTemplate.convertAndSend(destination, message);
}
}

JmsProducerTest.Class :

@RunWith(SpringRunner.class)
public class JmsProducerTest {

private static final String DESTINATION= "example";
private static final String MESSAGE= "message";

@InjectMocks
private JmsProducer jmsProducer;

@MockBean
JmsTemplate jmsTemplate;

@Before
public void init(){
    ReflectionTestUtils.setField(jmsProducer, "destinationQueue", DESTINATION);
}

@Test
public void testsend(){
    jmsProducer.send(MESSAGE);
    verify(jmsTemplate,times(1)).convertAndSend(DESTINATION, MESSAGE);
}
}

当我运行这个测试用例时,它给了我:java.lang.IllegalArgumentException: object is not an instance of declaring class

你对这个问题有什么想法吗?

【问题讨论】:

    标签: unit-testing spring-boot junit mockito spring-test


    【解决方案1】:

    如果您使用的是SpringRunner,则应将MockitoAnnotations.initMocks(this); 添加到init 方法中,因为@InjectMocks 将与MockitoJUnitRunner 一起正常工作。

    附言。 ReflectionTestUtils.setField(jmsProducer, "destinationQueue", DESTINATION); - 但您的字段有另一个名称 - destination,而不是 destinationQueue

    【讨论】:

      【解决方案2】:

      我还会注意到它也无法使用 jdk 1.8.05 模拟 JmsTemplate 和 ObjectMapper,当我将 JDK 更改为 1.8.74 时它工作得很好。

      我参考了discussion

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-22
        • 1970-01-01
        • 1970-01-01
        • 2016-05-08
        • 2012-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多