在 spring 引导测试中使用 @RestClientTest

Using @RestClientTest in spring boot test

我想使用 @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
    }
}

但是我得到 No qualifying bean of type 'org.springframework.web.client.RestTemplate' available 的错误。这当然是对的,因为我没有嘲笑它或使用 @ContextConfiguration 加载它。

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

找到了!由于我使用的是直接注入 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
    }
}