mockito 当我为下面的类编写Junit测试用例时,得到了“0个匹配器,1个已记录:“

ig9co6j1  于 2023-03-18  发布在  其他
关注(0)|答案(1)|浏览(114)

这是我的类,它有两个方法get和exchange,我不知道如何为下面的两个方法编写测试用例,因为我们使用的是**“new RestTemplate(new HttpComponentsClientHttpRequestFactory()).exchange”**我不知道如何模仿它。
以及如何为同一个类中的另一个方法编写测试用例

@Service
       public class TestServiceImpl implements TestService{

      @Override
          public Object get(String endpoint, ParameterizedTypeReference reference, boolean useToken) {
          ResponseEntity response = exchange(HttpMethod.GET, endpoint, null, reference, useToken);
           return response.getBody();
          }

      public ResponseEntity<Object> exchange(HttpMethod httpMethod, String endpoint, @Nullable                Object body, ParameterizedTypeReference<Object> reference, boolean useToken,String userId) {
 
           try {
            response = new RestTemplate(new HttpComponentsClientHttpRequestFactory()).exchange(endpoint, httpMethod, new HttpEntity<>(body, headers), reference);
            return response;
            } catch (Exception e) {
           e.printStackTrance
            }
         }
      }
      }



    @Test
     public void getTest(){
    IdmService idmService1 = Mockito.spy(idmService);
           Mockito.doReturn(TestData.getMockResponseEntity()).when(idmService1).exchange(any(),anyString(),any(),any(),anyBoolean());
      assertEquals(TestData.getMockResponseEntity().getBody(),idmService.get(endPoint,any(),true));
   }
 @Test
public void exchangeTest(){
  when(restTemplate.exchange(anyString(), ArgumentMatchers.any(HttpMethod.class),ArgumentMatchers.any(HttpEntity.class),
            ArgumentMatchers.any(HttpHeaders.class))).thenReturn(TestData.getMockResponseEntity())
    assertEquals(TestData.getMockResponseEntity().getBody(),idmService.get(endPoint,any(),true));

}
goqiplq2

goqiplq21#

当你这样创建RestTemplate时,你不能嘲笑它。
而是创建一个可以注入的工厂,并模拟该工厂以返回模拟RestTemplate

@Component
class RestTemplateFactory {
  public RestTemplate create() {
    return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
  }
}

然后在TestServiceImpl中:

public class TestServiceImpl implements TestService {
  private final RestTemplateFactory restTemplateFactory;

  @Autowired
  public TestServiceImpl(RestTemplateFactory restTemplateFactory) {
    this.restTemplateFactory = restTemplateFactory;
  }
  ...

最后在你的测试中

...
RestTemplateFactory factory = mock(RestTemplateFactory.class);
RestTemplate template = mock(RestTemplate.class);
TestServiceImpl service = new TestServiceImpl(factory);
when(factory.create()).thenReturn(template);
when(template.exchange(...)).thenReturn(...)

assertEquals(TestData.getMockResponseEntity().getBody(),service.get(...));
...

相关问题