java - 如何模拟 RestTemplate 的 webservice 响应?

标签 java spring unit-testing junit spring-test

<分区>

我想对我的整个应用程序编写一个集成测试,并且只想模拟一个特定的方法:我用来将一些数据发送到外部网络服务并接收响应的 RestTemplate .

我想从本地文件读取响应(模拟和模仿外部服务器响应,所以它总是一样的)。

我的本​​地文件应该只包含在生产环境中外部网络服务器会响应的json/xml响应。

问题:如何模拟外部 xml 响应?

@Service
public class MyBusinessClient {
      @Autowired
      private RestTemplate template;

      public ResponseEntity<ProductsResponse> send(Req req) {
               //sends request to external webservice api
               return template.postForEntity(host, req, ProductsResponse.class);
      }
}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

   @Test
   public void test() {
        String xml = loadFromFile("productsResponse.xml");
        //TODO how can I tell RestTemplate to assume that the external webserver responded with the value in xml variable?
   }
}

最佳答案

Spring 真好:

    @Autowired
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;

    @Before
    public void createServer() throws Exception {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Test
    public void test() {
        String xml = loadFromFile("productsResponse.xml");
        mockServer.expect(MockRestRequestMatchers.anything()).andRespond(MockRestResponseCreators.withSuccess(xml, MediaType.APPLICATION_XML));
    }

关于java - 如何模拟 RestTemplate 的 webservice 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47715980/

相关文章:

java - 重构依赖过多的服务

java - Controller 类中的 Spring MVC 本地化不起作用

Java Mockito 使用真实方法而不是使用模拟方法

java - 我正在尝试在 android 日志中打印或写入 protected file/data/data/com.package/file

java - 如何在 spring security 登录后恢复表单?

java - 元素在点 (x,y) 处不可点击,但其他元素会收到点击

c# - XML 反序列化单元测试

java - 将对象添加到 Jpanel

spring - Azure Databricks 日志记录配置问题

java - "Too few invocations"但方法被调用并且所有内容都是使用 GroovySpy 或 GroovyMock 创建的