引发异常时,我可以以某种方式使用doAnswer()
吗?
我在集成测试中使用它来获取方法调用,并在配置@RabbitListenerTest
中进行测试...
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyIT {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private MyRabbitListener myRabbitListener;
@Autowired
private RabbitListenerTestHarness harness;
@Test
public void testListener() throws InterruptedException {
MyRabbitListener myRabbitListener = this.harness.getSpy("event");
assertNotNull(myRabbitListener);
final String message = "Test Message";
LatchCountDownAndCallRealMethodAnswer answer = new LatchCountDownAndCallRealMethodAnswer(1);
doAnswer(answer).when(myRabbitListener).event(message);
rabbitTemplate.convertAndSend("exchange", "key", message);
assertTrue(answer.getLatch().await(20, TimeUnit.SECONDS));
verify(myRabbitListener).messageReceiver(message);
}
@Configuration
@RabbitListenerTest
public static class Config {
@Bean
public MyRabbitListener myRabbitListener(){
return new MyRabbitListener();
}
}
}
可以,但是当我引入被抛出的
Exception
时,它不是这有效
@RabbitListener(id = "event", queues = "queue-name")
public void event(String message) {
log.info("received message > " + message);
}
这不是
@RabbitListener(id = "event", queues = "queue-name")
public void event(String message) {
log.info("received message > " + message);
throw new ImmediateAcknowledgeAmqpException("Invalid message, " + message);
}
任何帮助表示赞赏
最佳答案
LatchCountDownAndCallRealMethodAnswer
是非常基本的
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
invocation.callRealMethod();
this.latch.countDown();
return null;
}
您可以将其复制到新类,然后将其更改为类似
private volatile Exception exeption;
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
try {
invocation.callRealMethod();
}
catch (RuntimeException e) {
this.exception = e;
throw e;
}
finally {
this.latch.countDown();
}
return null;
}
public Exception getException() {
return this.exception;
}
然后
assertTrue(answer.getLatch().await(20, TimeUnit.SECONDS));
assertThat(answer.getException(), isInstanceOf(ImmediateAcknowledgeAmqpException.class));
请打开github问题;框架应立即提供支持。
关于java - Mockito doAnswer(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59239444/