【问题标题】:How to mock rest template and response entity如何模拟休息模板和响应实体
【发布时间】:2021-06-24 21:31:52
【问题描述】:

我是 JUnit 和 Mockito 概念的新手,并试图弄清楚它是如何在 rest 模板调用中完成的。 考虑下面的粗略实现,

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(...);
     }

}

现在我需要以这样一种方式编写单元测试,我必须模拟其余的模板调用和
检查状态码是否为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);

  }
}

如果这不是实现的方式,请纠正我。

【问题讨论】:

    标签: java spring-boot unit-testing junit mockito


    【解决方案1】:

    Rest 模板重载方法 postForEntity 多次。确保您定义了正确的。此外,您可以使用 anyString() 代替 'local...'。

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

    【讨论】:

      【解决方案2】:

      您可以使用单独的服务来维护所有模拟响应。 Wiremock 是您可以使用的一种有用的应用程序。您还可以拥有 HTTP 请求/响应和状态代码的所有可能组合。 使用wiremock,您还可以创建单独的请求-响应映射文件,这对于避免硬编码很有用。 http://wiremock.org/docs/getting-started/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-08
        • 2021-08-16
        • 2019-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        相关资源
        最近更新 更多