如何用 Mockito 模拟 JmsTemplate?
How to mock JmsTemplate with Mockito?
我尝试测试 class 我发送 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
你对这个问题有什么想法吗?
如果您正在使用 SpringRunner
,您应该添加到 init
方法 MockitoAnnotations.initMocks(this);
,因为 @InjectMocks
将与 MockitoJUnitRunner
一起工作。
PS。 ReflectionTestUtils.setField(jmsProducer, "destinationQueue", DESTINATION);
- 但您的字段有另一个名称 - destination
,而不是 destinationQueue
我还注意到它无法使用 jdk 1.8.05 模拟 JmsTemplate 和 ObjectMapper,当我将 JDK 更改为 1.8.74 时效果很好。
我参考了 discussion
我尝试测试 class 我发送 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
你对这个问题有什么想法吗?
如果您正在使用 SpringRunner
,您应该添加到 init
方法 MockitoAnnotations.initMocks(this);
,因为 @InjectMocks
将与 MockitoJUnitRunner
一起工作。
PS。 ReflectionTestUtils.setField(jmsProducer, "destinationQueue", DESTINATION);
- 但您的字段有另一个名称 - destination
,而不是 destinationQueue
我还注意到它无法使用 jdk 1.8.05 模拟 JmsTemplate 和 ObjectMapper,当我将 JDK 更改为 1.8.74 时效果很好。
我参考了 discussion