使用 WireMock 的 Junit 测试抛出 404 not found 期望

问题描述

我从一个星期以来就遇到了这个问题,我没有找到足够的资源。 我有一个使用外部 API 的 Java 应用程序,我想使用 wiremock 测试我的应用程序。

当我想发送文件时,它总是显示 404 Not found。 我发现问题是wiremock 没有保留Host 标头值,所以我在下面有这个代码,但它总是不起作用。

我尝试了真正的 API,它使用 wiremock Record & Playback 功能完美运行,但我指定了 -preserve-host-header 选项(没有这个,它会得到 404 Not Found)

我要测试的服务(我没有控制器):

@Service
public class Bank{
    //This method is working
    public String hello(String hello){
        return exernalAPI.get("hello").toString(); // It's just an example
    }
    //This method is not working in test(404)
    public void uploadFile(String inputStrum...){
       //The code here is used to send the file to an external API using method post
    }
}

我做了一个记录和回放来捕获来自真实外部 API 的请求和响应,

课堂测试:

@AutoConfigurewiremock(port=0)
@ContextConfiguration(classes={Bank.class})
public class BankTest{

@Autowired
public Bank bank;
@Test //The test is passing
public void hellotest(){
    String expected = resourse.getResource("classpath:response/helloMessage.txt").toString(); //Get the captured response
    String actual = bank.hello("Jack"); //this return Hi Jack and it's working
    assertEquals(expected,actual);
}
@Test //This test is not passing
public String uploadFiletest(){
     InputSteam is = getInputStream();
     //code to get inputStream 
     Resource expected= resourse.getResourse("classpath:responses/upload_response.json");
     String expected = expected.toString();

     is.setContent(resource.getResource("classpath:file_to_upload.zip"));

     String actual = bank.uploadFile(is); // Here i have 404 not found
     assertEquals(expected,actual);

}

经过几次搜索后,我发现我必须使用以下内容保留 Host 标头:

preserveHostHeader(true);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)