在春季启动测试中使用@RestClientTest

时间:2019-01-30 06:39:36

标签: spring-boot spring-rest 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?还是我理解错了?

1 个答案:

答案 0 :(得分:2)

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