首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嘲弄RestTemplate postforEntity

嘲弄RestTemplate postforEntity
EN

Stack Overflow用户
提问于 2021-02-02 13:44:23
回答 2查看 1K关注 0票数 2

我有个服务舱,看上去-

代码语言:javascript
复制
class A {
   @Autowired
   RestTemplate restTemplate;
   public void method() {
       res = restTemplate.postForEntity("http://abc", entity, Employee.class);
       resBody = res.getBody();      
   }
}

以下是它的测试课程-

代码语言:javascript
复制
class TestA {
   @Mock
   RestTemplate restTemplate;
   @InjectMocks
   A obj;
   void testMethod1() {
       res = ....
       when(restTemplate.postForEntity(any(), any(), any()).thenReturn(res);
   }
   void testMethod2() {
       res = ....
       when(restTemplate.postForEntity(anyString(), any(), any()).thenReturn(res);
   }
}

testMethod1在"res.getBody() from A.method()“上抛出NullPointerException失败,而testMethod2成功运行

为什么在anyString()工作时没有()在这里工作?我认为任何()都适用于任何数据类型。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-02 18:36:39

看看Javadocs for RestTemplate。有三种postForEntity方法:

  • postForEntity(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)
  • postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)
  • postForEntity(URI url, Object request, Class<T> responseType)

testMethod2中的模拟可以肯定地捕捉到这两种方法中的一种。但是,您的testMethod1中的模拟似乎用URI作为第一个参数来覆盖该方法,因此您的restTemplate.postForEntity("http://abc", entity, Employee.class)不匹配。

如果您对当前模拟的方法感兴趣,只需键入一行,例如restTemplate.postForEntity(any(), any(), any()),然后在您喜爱的IDE中的方法上悬停以查看编译时已经覆盖的确切(重写)方法。

票数 3
EN

Stack Overflow用户

发布于 2022-02-27 10:55:09

我的问题与此相似,将空转换为对我有用的字符串:when(restTemplateMock.postForEntity((String)isNull(), any(), eq(List.class))) .thenReturn(responseEntityMock);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66010969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档