gpt4 book ai didi

spring-boot - 在 spring boot 测试中使用@RestClientTest

转载 作者:行者123 更新时间:2023-12-02 03:22:11 25 4
gpt4 key购买 nike

我想使用 @RestClientTest 为下面的组件编写一个简单的测试(注意:我可以不使用 @RestClientTest 并且模拟依赖 bean,效果很好。)。

@Slf4j
@Component
@RequiredArgsConstructor
public class NotificationSender {

private final ApplicationSettings settings;
private final RestTemplate restTemplate;

public ResponseEntity<String> sendNotification(UserNotification userNotification)
throws URISyntaxException {
// Some modifications to request message as required
return restTemplate.exchange(new RequestEntity<>(userNotification, HttpMethod.POST, new URI(settings.getNotificationUrl())), String.class);
}
}

和测试;

@RunWith(SpringRunner.class)
@RestClientTest(NotificationSender.class)
@ActiveProfiles("local-test")
public class NotificationSenderTest {

@MockBean
private ApplicationSettings settings;
@Autowired
private MockRestServiceServer server;
@Autowired
private NotificationSender messageSender;

@Test
public void testSendNotification() throws Exception {
String url = "/test/notification";
UserNotification userNotification = buildDummyUserNotification();
when(settings.getNotificationUrl()).thenReturn(url);
this.server.expect(requestTo(url)).andRespond(withSuccess());

ResponseEntity<String> response = messageSender.sendNotification(userNotification );

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}

private UserNotification buildDummyUserNotification() {
// Build and return a sample message
}
}

但我收到错误消息,没有可用的类型为“org.springframework.web.client.RestTemplate”的合格 bean。这当然是对的,因为我没有 mock 它或使用 @ContextConfiguration 来加载它。

@RestClientTest不就是配置了一个RestTemplate吗?还是我理解错了?

最佳答案

找到了!由于我使用的是直接注入(inject) RestTemplate 的 bean,因此我们必须将 @AutoConfigureWebClient(registerRestTemplate = true) 添加到解决此问题的测试中。

这是在 @RestClientTest 的 javadoc 中,我之前似乎忽略了它。

测试成功;

@RunWith(SpringRunner.class)
@RestClientTest(NotificationSender.class)
@ActiveProfiles("local-test")
@AutoConfigureWebClient(registerRestTemplate = true)
public class NotificationSenderTest {

@MockBean
private ApplicationSettings settings;
@Autowired
private MockRestServiceServer server;
@Autowired
private NotificationSender messageSender;

@Test
public void testSendNotification() throws Exception {
String url = "/test/notification";
UserNotification userNotification = buildDummyUserNotification();
when(settings.getNotificationUrl()).thenReturn(url);
this.server.expect(requestTo(url)).andRespond(withSuccess());

ResponseEntity<String> response = messageSender.sendNotification(userNotification );

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}

private UserNotification buildDummyUserNotification() {
// Build and return a sample message
}
}

关于spring-boot - 在 spring boot 测试中使用@RestClientTest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54434637/

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