简体   繁体   English

如何模拟 rest 模板和响应实体

[英]How to mock rest template and response entity

I m new to JUnit and Mockito concepts and trying to figure out how it's done in a rest template call.我是 JUnit 和 Mockito 概念的新手,并试图弄清楚它是如何在 rest 模板调用中完成的。 Consider the below rough implementation,考虑下面的粗略实现,

Class TheWrapper{

  @Autowired
  RestTemplate template;

}

Class Abc extends TheWrapper{

  boolean validation(){

      // .....
     //carries out different validation operations
     //  .....

     try{
       
        ResponseEntity<Object> response= template.postForEntity("localhost:8080...",obj,Object.class);

        if(response.getStatusCodeValue()==200) // Problem: throwing MyCustomException here, 
                                               // when test is runned
          return true;
        else
          return false;
     
     }catch(Exception e){
        throws new MyCustomException(...);
     }

}

Now I need to write unit testing in such a way that, I have to mock the rest template call and现在我需要以这样一种方式编写单元测试,我必须模拟 rest 模板调用和
check whether the status code is 200 or not.检查状态码是否为 200。

Class Testing{

  @InjectMock
  Abc obj;

  @Mock
  RestTemplate template;

  @BeforeEach
  void setup(){
    obj=new Abc();
    MockitoAnnotations.initMocks(this);
   }

  @Test
  void testingIt(){
    
   ResponseEntity<Object> response=new ResponseEntity<Object>(HttpStatus.OK);
  
   when(template.postForEntity("local...",any(),any())).then(response)

   Assertion.assertEquals(obj.validation(),true);

  }
}

If this is not the way to implement, please do correct me.如果这不是实施方式,请纠正我。

Rest template overloaded method postForEntity multiple times. Rest 模板重载方法postForEntity多次。 Make sure you define the correct one.确保您定义了正确的。 Also, you can use anyString() instead of 'local...'.此外,您可以使用anyString()而不是 'local...'。

template.postForEntity(anyString(),any(),any())

You can use a separate service to maintain all mock response.您可以使用单独的服务来维护所有模拟响应。 Wiremock is one such useful application you can use. Wiremock 是您可以使用的一种有用的应用程序。 You can have all possible combination of HTTP request/response, and status code as well.您可以拥有 HTTP 请求/响应和状态码的所有可能组合。 Using wiremock you can also create separate files of request-response mapping, which can be useful in avoiding hardcoding.使用wiremock,您还可以创建单独的请求-响应映射文件,这对于避免硬编码很有用。 http://wiremock.org/docs/getting-started/ http://wiremock.org/docs/getting-started/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM