当前位置: 首页 > 知识库问答 >
问题:

Pact:未找到响应类型的HttpMessageConverter

郝永思
2023-03-14

BookServiceInterfaceImpl.java

@Service("bookService")
public class BookServiceInterfaceImpl implements BookServiceInterface {

public ResponseEntity<List<String>> getBookTitlesForCourse(final String courseId){
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String[]> response = restTemplate.getForEntity("http://localhost:8888/api/book/course/" + courseId, String[].class);
    List<String> titles = Arrays.asList(response.getBody());
    return new ResponseEntity<List<String>>(titles, HttpStatus.OK);
}
}

BookController.java

@RestController
@RequestMapping("/api")
public class BookController {

private BookService bookService;

@Autowired
public BookController(BookService bookService) {
    this.bookService = bookService;
}

@RequestMapping(method = RequestMethod.GET, value="/book/course/{id}")
public ResponseEntity<String[]>getBookTitlesForCourse(@PathVariable("id") final long id) {
    List<Book> books = bookService.findAllBooks();
    if(books.isEmpty()) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    String[] bookTitles = books.stream()
            .filter(book -> book.getCourseId() == id)
            .map(book -> book.getTitle())
            .toArray(String[]::new);
    return new ResponseEntity<String[]>(bookTitles, HttpStatus.OK);
}
}

我正试图用Pact在两人之间建立一个契约。到目前为止,我在Consumer中进行了以下测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class BookServiceTest {

@Rule
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);

@Pact(provider="test_provider", consumer="test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
    return builder
            .given("test state")
            .uponReceiving("BookServiceTest test interaction")
                .path("/api/book/course/1")
                .method("GET")
            .willRespondWith()
                .status(200)
                .body("{[\"Dont make me think\",\"Clean Code\"]}")
            .toPact();
}

@Test
@PactVerification("test_provider")
public void test_retrieveBooksForcourse_validCourseId_success() {
    //given
    final String courseId = "1";
    BookServiceInterfaceImpl bookService = new BookServiceInterfaceImpl();
    //when
    ResponseEntity<List<String>> response = bookService.getBookTitlesForCourse(courseId);
    //then:
    assertThat(response.getStatusCode(), is(200));
    assertThat(response.getBody().size(), is(2));
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.ocr</groupId>
<artifactId>new-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>new-consumer</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
    <relativePath />
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>au.com.dius</groupId>
        <artifactId>pact-jvm-consumer-junit_2.11</artifactId>
        <version>3.5.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

当我运行它时,我会得到以下信息:

java.lang.AssertionError: Pact Test function failed with an exception: Could not extract response: no suitable HttpMessageConverter found for response type [class [Ljava.lang.String;] and content type [application/octet-stream]
at au.com.dius.pact.consumer.BaseProviderRule.validateResult(BaseProviderRule.java:164)
at au.com.dius.pact.consumer.BaseProviderRule$1.evaluate(BaseProviderRule.java:77)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class [Ljava.lang.String;] and content type [application/octet-stream]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:110)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:917)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:901)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:655)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:312)
at com.ocr.newconsumer.service.BookServiceInterfaceImpl.getBookTitlesForCourse(BookServiceInterfaceImpl.java:29)
at com.ocr.newconsumer.controller.BookServiceTest.test_retrieveBooksForcourse_validCourseId_success(BookServiceTest.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at au.com.dius.pact.consumer.BaseProviderRule.lambda$runPactTest$1(BaseProviderRule.java:150)
at au.com.dius.pact.consumer.BaseMockServer.runAndWritePact(MockHttpServer.kt:152)
at au.com.dius.pact.consumer.ConsumerPactRunnerKt.runConsumerTest(ConsumerPactRunner.kt:13)
at au.com.dius.pact.consumer.BaseProviderRule.runPactTest(BaseProviderRule.java:148)
at au.com.dius.pact.consumer.BaseProviderRule.access$100(BaseProviderRule.java:21)
at au.com.dius.pact.consumer.BaseProviderRule$1.evaluate(BaseProviderRule.java:76)
... 20 more
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at au.com.dius.pact.consumer.BaseProviderRule.lambda$runPactTest$1(BaseProviderRule.java:150)
at au.com.dius.pact.consumer.BaseMockServer.runAndWritePact(MockHttpServer.kt:152)
at au.com.dius.pact.consumer.ConsumerPactRunnerKt.runConsumerTest(ConsumerPactRunner.kt:13)
at au.com.dius.pact.consumer.BaseProviderRule.runPactTest(BaseProviderRule.java:148)
at au.com.dius.pact.consumer.BaseProviderRule.access$100(BaseProviderRule.java:21)
at au.com.dius.pact.consumer.BaseProviderRule$1.evaluate(BaseProviderRule.java:76)
... 20 more

所以我不是真正的问题所在,根据我所知,我很确定这种转换不应该是一件大事情,应该由Spring来处理。关于REST调用或测试(第一次使用Pact),我是否做错了什么?我是否在pom中缺少了一个我假定Spring Boot父/依赖项会有的依赖项?

共有1个答案

傅长恨
2023-03-14

对于我们的使用者测试,我们扩展了consumerpacttestmk2。必须重写的方法之一是runtest(MockServer ms)runtest方法中的mockserver具有您需要使用的URL的主机部分。因此您需要更改imple类中的URL以使用增强的URL。

public class BookServiceInterfaceImpl implements BookServiceInterface {
    private String hostUrl = "http://localhost:8888";
    //provider setter for this variable.

这样,您就可以使用hosturl创建最终的URL。

ResponseEntity<String[]> response = restTemplate.getForEntity(hostUrl + "/api/book/course/" + courseId, String[].class);

然后在runtest方法中。

@Override
protected void runTest(MockServer ms) throws IOException {
    BookServiceInterfaceImpl bookService = new BookServiceInterfaceImpl();
    bookService.setHostUrl(ms.getUrl());
 类似资料:
  • 我是新的Spring集成和工作在Spring集成超文本传输协议模块为我的项目要求。我从出站网关作为超文本传输协议客户端发送请求。我试图向服务器发起一个请求,服务器应该用我的设置值返回消息负载。我正在将对象转换为JSON,用于发送到服务器我正在从客户端(HttpClientDemo)向服务器端的入站网关发送请求。为此,我将我的对象转换成JSON,然后将JSON字符串转换为客户端的对象,在那里执行一些

  • 首先,抱歉可能重复。我发现了一些关于类似问题的问题。然而,我仍然想不出我的具体情况出了什么问题。 所以,例如json从服务器: 我生成了名为Mall的类(以及数据结构其余部分的所有子类): 服务器返回内容类型text/plain。为了修改内容类型,我编写了简单的扩展类: 最后,这是我试图使用我的网络服务的方式: 然而,我仍然得到同样的例外: 无法提取响应:未找到响应类型[m.m.restsprin

  • 当通过Rest Api发布请求时,我抛出 内容类型:应用程序/json 当我尝试编写代码时,我使用以下代码 org.springframework.web.client.RestClientException:无法提取响应:没有找到合适的HttpMessageConverter响应类型[... FileUpload响应DTO]和内容类型[text/html]给出一个错误。如何转换?

  • 我正在尝试使用spring for Android从REST服务中检索一些数据。但是我遇到了问题。我也在使用Robospice——因此有一种类似这样的方法: 不幸的是,这不起作用。我将引发以下异常: 现在,基于我的谷歌搜索,我觉得我需要添加一个消息转换器。我只是不确定我需要哪个消息转换器,或者在哪里添加它?

  • 问题内容: 使用spring,使用以下代码: 我懂了 pojo的片段: 问题答案: 从Spring的角度来看,没有一个通过注册的实例可以将内容转换为对象。感兴趣的方法是。上述所有回报的实现,包括。 由于没有人可以读取您的HTTP响应,因此处理失败,并出现异常。 如果你能控制服务器响应,修改设置到,或东西匹配。 如果您不控制服务器响应,则需要编写和注册自己的(可以扩展Spring类,see 及其子类

  • org.springframework.web.client.未知内容类型异常:无法提取响应:没有找到适合响应类型[类net.minidev.json.JSONObject]和内容类型[应用程序/json]的HttpMessageConzer endpoint Url还返回JSONObject,因此不知道为什么不匹配