如何模拟休息模板和响应实体

How to mock rest template and response entity

我是 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);

  }
}

如果不是这样实现的,请指正。

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

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

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