【问题标题】:unable to mock the resttemplate call using restclienttest无法使用 restclienttest 模拟 resttemplate 调用
【发布时间】:2020-07-28 22:50:06
【问题描述】:

我想模拟使用RestTemplateBuilderRestTemplate。因此,我使用restclienttest

很遗憾,我无法模拟 resttemplate 调用。 当Sup supExpected = myService.getDetails("1234") 被调用时,它正在执行完整的后端调用,而不是导致我要求做的事情。

它不是生成自定义 json 字符串“SD”,而是执行实际的 GET 调用并从后端给出响应。

这是我的junit代码:

@RunWith(SpringRunner.class)
@RestClientTest(MyService.class)
public class TestMyServiceApplication {


    @Autowired
    private MyService myService; 

     @Autowired
        private RestTemplate restTemplate;

    @Autowired 
    private MockRestServiceServer server;       

    @Before public void setUp() { 
     server= MockRestServiceServer.createServer(restTemplate); }

    @Test
    public void ReturnSupplierSuccessfully() {

        String SD= "{\"SUP\": {\"LNR\": \"1234\",\"NAME1\": \"RestClient\"}]}}";
        this.server
        .expect(requestTo("abc.net/service/v1?lnr=1234"))
        .andExpect(method(HttpMethod.GET))
        .andRespond(withSuccess(SD, MediaType.APPLICATION_JSON));

        Sup supExpected = myService.getDetails("1234");

        server.verify();
        assertNotNull(supExpected);
    }

谁能帮我看看我的代码有什么问题?

【问题讨论】:

  • 请尝试以下操作。 1) 删除setUp() 方法。 2)修改requestTo("/service/v1?lnr=1234)
  • @R.G 不幸的是,这对我没有帮助。我重新设计了我们的服务等级。然后它开始工作了。

标签: java spring-boot junit4 spring-junit


【解决方案1】:

尝试将@Mock 注解放在 RestTemplate 和其他相应的服务类之上。

@Mock

【讨论】:

  • 在这种情况下,我使用的是@restclienttest,为了使用@Mok:我必须使用mockito 框架。由于我的服务中有 RestTemplateBuilder,mockito 没有帮助我,因此我想尝试使用 @restclienttest
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2014-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多