标签: mockrestserviceserver

使用@RestClientTest对rest客户端进行Spring启动测试

我正在使用spring boot 1.5.8并想测试我的客户端:

@Component
public class RestClientBean implements RestClient {
  private Map<String, RestTemplate> restTemplates = new HashMap<>();

  @Autowired
  public RestClientBean(RestTemplateBuilder builder, SomeConfig conf) {
    restTemplates.put("first", builder.rootUri("first").build();
    restTemplates.put("second", builder.rootUri("second").build();
  }
}
Run Code Online (Sandbox Code Playgroud)

通过以下测试:

@RunWith(SpringRunner.class)
@RestClientTest(RestClient.class)
public class RestClientTest {
  @Autowired
  private RestClient client;

  @Autowired
  private MockRestServiceServer server;

  @TestConfiguration
  static class SomeConfigFooBarBuzz {
    @Bean
    public SomeConfig provideConfig() {
        return new SomeConfig(); // btw. not sure why this works, 
                                 // but this is the only way 
                                 // I got rid of the "unable to …
Run Code Online (Sandbox Code Playgroud)

java resttemplate spring-boot-test mockrestserviceserver

8
推荐指数
1
解决办法
5059
查看次数

我如何对javanica @HystrixCommand注释方法进行单元测试?

我正在使用javanica并注释我的hystrix命令方法,如下所示:

@HystrixCommand(groupKey="MY_GROUP", commandKey="MY_COMMAND" fallbackMethod="fallbackMethod")
public Object getSomething(Object request) {
....
Run Code Online (Sandbox Code Playgroud)

我试图对我的回退方法进行单元测试,而不必直接调用它们,即我想调用带@HystrixCommand注释的方法,并在抛出500错误后让它自然地流入回退.这一切都在单元测试之外工作.

在我的单元测试中,我使用弹簧MockRestServiceServer返回500个错误,这部分正在工作,但Hystrix没有在我的单元测试中正确初始化.在我的测试方法开始时,我有:

HystrixRequestContext context = HystrixRequestContext.initializeContext();
myService.myHystrixCommandAnnotatedMethod();
Run Code Online (Sandbox Code Playgroud)

在此之后,我试图通过键获取任何hystrix命令并检查是否有任何已执行的命令,但列表始终为空,我使用此方法:

public static HystrixInvokableInfo<?> getHystrixCommandByKey(String key) {
    HystrixInvokableInfo<?> hystrixCommand = null;
    System.out.println("Current request is " + HystrixRequestLog.getCurrentRequest());
    Collection<HystrixInvokableInfo<?>> executedCommands = HystrixRequestLog.getCurrentRequest()
            .getAllExecutedCommands();
    for (HystrixInvokableInfo<?> command : executedCommands) {
        System.out.println("executed command is " + command.getCommandGroup().name());
        if (command.getCommandKey().name().equals(key)) {
            hystrixCommand = command;
            break;
        }
    }
    return hystrixCommand;
}
Run Code Online (Sandbox Code Playgroud)

我意识到我在单元测试初始化​​中遗漏了一些东西,任何人都可以指出我正确的方向如何正确地进行单元测试吗?

java unit-testing annotations hystrix mockrestserviceserver

7
推荐指数
2
解决办法
5508
查看次数

MockRestServiceServer 如何仅验证不包括查询字符串的请求路径

我有一个@ComponentDataClientImpl,它使用RestTemplate. API端点具有查询参数,这些参数在调用时传递RestTemplate。有一个@RestClientTestTest 类DataApiClientImplTest测试DataClientImpl,使用 模拟 REST 调用MockRestServiceServer

在测试方法中,我想验证 API 调用中是否使用了正确的端点路径和查询参数(特别是名称)。使用MockRestRequestMatchers.requestTo()MockRestRequestMatchers.queryParam()方法进行验证。

MockRestRequestMatchers.requestTo()运行测试时失败。它似乎将包含查询字符串的实际 url 与不带查询字符串的预期 url(传递给MockRestRequestMatchers.requestTo()method.

在pom中,我正在使用

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.0</version>
    <relativePath/> 
</parent>
Run Code Online (Sandbox Code Playgroud)

代码如下。

@RestClientTest(DataApiClientImpl.class)
@AutoConfigureWebClient(registerRestTemplate = true)
class DataApiClientImplTest {

    private static final String OBJECT_ID_URI = "http://localhost:8080/testBucketId/objects/test-obj-id";

    @Autowired
    private DataApiClientImpl dataApiClientImpl;

    @Autowired
    private MockRestServiceServer mockRestServiceServer;

    @Test
    void testApiCall() {
        mockRestServiceServer.expect(MockRestRequestMatchers.requestTo(OBJECT_ID_URI))
                .andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
                .andExpect(MockRestRequestMatchers.queryParam("keyid", CoreMatchers.anything()))
                .andExpect(MockRestRequestMatchers.queryParam("token", CoreMatchers.anything()))
                .andRespond(MockRestResponseCreators.withSuccess("dummy", MediaType.APPLICATION_JSON));

        String response = dataApiClientImpl.getItem("asdf12345", …
Run Code Online (Sandbox Code Playgroud)

java resttemplate spring-boot mockrestserviceserver

6
推荐指数
2
解决办法
3618
查看次数

如何使用 spring 的 MockRestServiceServer 模拟同一请求的多个响应?

我使用 MockRestServiceServer 来模拟 http 响应。在特定场景中,我两次调用端点并希望第二次得到不同的响应。

但是当我写下第二个期望时,它就像覆盖了我的第一个期望。

如何为同一个请求编写多个响应?

spring integration-testing spring-test-mvc mockrestserviceserver

5
推荐指数
1
解决办法
1960
查看次数

使用 TestRestTemplate 和 MockRestServiceServer 时,解析异常而不是实体列表不起作用

我有一个简单的控制器(代码

@RestController
@RequestMapping("/profiles" , produces = [MediaType.APPLICATION_JSON_VALUE])
class Controller(@Autowired val restClient: RestClient) {

    @GetMapping("/simple-get")
    fun simpleGetCall(): List<Profile> {
        restClient.callClientGet()
        return listOf(
                    Profile("firstname1", "lastname1"),
                    Profile("firstname2", "lastname2"))
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器正在调用 RestClient 进行客户端调用(代码

@Service
class RestClient(@Autowired val restTemplate: RestTemplate) {
    fun callClientGet(){
        try {
            restTemplate.getForEntity(
                "/profiles/simple-get",
                Number::class.java
            )
        }catch(exception: Exception){
            throw MyClientCallException("this is an exception")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

MyClientCallException 看起来像这样(代码

class MyClientCallException(message: String) :
    ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, message)
Run Code Online (Sandbox Code Playgroud)

我的班级中有 3 个功能测试(代码)我使用org.springframework.test.web.client.MockRestServiceServer作为服务器

@Test
fun `when calling …
Run Code Online (Sandbox Code Playgroud)

java json kotlin mockrestserviceserver jsonparser

5
推荐指数
1
解决办法
103
查看次数

MockRestServiceServer 中是否有现成的类来捕获请求正文以进行日志记录等?

我会自己回答我的问题,但我对我的解决方案不满意,所以如果有现成的便利类/方法做同样的事情,请告诉我。

问题陈述

我在单元测试中使用 Spring MockRestServiceServer来模拟 REST 服务调用。我想快速访问模拟 REST 服务器的请求正文。通常用于记录或仅用于在调试期间进行评估。

使用上下文如下:

import org.springframework.test.web.client.MockRestServiceServer;

class MyTest {
    @Test
    void myTest() {
        MockRestServiceServer mockServer = ...;
        mockServer
            .expect(MockRestRequestMatchers.method(HttpMethod.POST))
            .andExpect(MockRestRequestMatchers.requestTo("http://mock.example.com/myservice"))

            // The following method does not exist, it's what I'd like to have
            .andCapture(body -> { 
                /* do something with the body */ 
                log.info(body);
            }) // the place for the Captor

            .andRespond(MockRestResponseCreators.withSuccess("The mock response", MediaType.TEXT_PLAIN))
        ;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题

是否有现成的类/方法可以提供andCapture(body -> {})开箱即用的“”功能?

java spring unit-testing mocking mockrestserviceserver

2
推荐指数
1
解决办法
1353
查看次数