gpt4 book ai didi

java - 在测试主题类中调用时,Mockbean 不会抛出错误

转载 作者:行者123 更新时间:2023-12-02 10:29:47 25 4
gpt4 key购买 nike

似乎返回 void 的模拟bean 在测试对象内部调用时不会抛出错误。我可以在外面调用它,但它会抛出错误。我的使用方式有问题吗?

//some imports ...
@RunWith(SpringRunner.class)
@SpringBootTest(classes={ MessagingController.class })
public class MessagingControllerTest {
@Autowired
private MessagingController controller;

@MockBean
private RabbitMessagingTemplate rabbitMessagingTemplate;

@Test
public void testPublishMessageConversionException() {
//given:
Message message = new Message(null, null, null);

//when:
doThrow(MessageConversionException.class).when(rabbitMessagingTemplate).convertAndSend(any());
ResponseEntity<?> response = controller.publish(message);
// rabbitMessagingTemplate.convertAndSend() // this throws the error
//then:
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);

verify(rabbitMessagingTemplate).convertAndSend(message.getExchange(), message.getRoutingKey(), message.getPayload());
}

...

}

最佳答案

如果你只是想进行单元测试,为什么要使用整个 spring 上下文?在我看来,SpringRunner 对于集成和 e2e 测试非常有用,但对于单元测试,您应该坚持使用 MockitoJUnitRunner。像这样的东西应该有效:

@RunWith(MockitoJUnitRunner.class)
public class MessagingControllerTest {
@Mock
private RabbitMessagingTemplate rabbitMessagingTemplate;

@InjectMocks
private MessagingController controller;

@Test
public void testPublishMessageConversionException() {
//given:
Message message = mock(Message.class);

//when:
when(rabbitMessagingTemplate.convertAndSend(anyObject()).thenThrow(new MessageConversionException());
try {
ResponseEntity<?> response = controller.publish(message);
fail();
} catch (MessageConversionException mce) {
//then:
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);

verify(rabbitMessagingTemplate, times(1)).convertAndSend(message.getExchange(), message.getRoutingKey(), message.getPayload());
}
}

...

}

关于java - 在测试主题类中调用时,Mockbean 不会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53678182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com