在为 Spring 控制器执行 JUnit 测试用例时出现 I/O 错误



我正在执行一个测试用例来调用弹簧控制器(GET方法(。但是,它会引发低于 I/O 错误。

org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8039": Connect to localhost:8039 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:8039 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:674)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:636)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)

下面是我正在执行的测试用例类,它抛出了上述错误。

public class GetRuleSetsTests extends PreferencesAdminClientTestApplicationTests<GetRuleSetsResponse>{
@Test
public void testSuccess() throws Exception
{
final String mockedResponseJson = rawJsonFromFile("com/cnanational/preferences/client/rule-sets/getRuleSetsResponse.json");
MockRestServiceServer mockServer = mockServer();
mockServer.expect(requestTo(dummyUri()))
.andExpect(method(HttpMethod.GET))
.andExpect(queryParam("ruleSetDescription", "TestRuleDescription"))
.andRespond(withSuccess(
mockedResponseJson,
MediaType.APPLICATION_JSON));
ServiceClientResponse<GetRuleSetsResponse> response = executeDummyRequest();
mockServer.verify();
assertThat(response.isSuccessful(), equalTo(true));
GetRuleSetsResponse programResponse = response.getParsedResponseObject();
assertThat(programResponse.getRuleSets().size(), equalTo(2));
}
@Override
public URI dummyUri() {
return UriComponentsBuilder.fromUri(baseUri())
.path(this.endpointProperties.getRuleSets())
.build()
.toUri();
}
}

我错过了什么?任何投入都值得赞赏。

如果您已正确配置测试环境以运行MockRestServiceServer

(我的意思是@RunWith(SpringRunner.class)@RestClientTest(ClassUnderTestThatCallsTheMockServer.class)(,确保您没有使用= new MockServer()实例化您的模拟服务器,而只是使用从 spring 上下文中@Autowired的实例(因为该实例是开箱即用的(。

我看到您在测试中有很多继承和覆盖的方法,使用this.returnSomething...调用事物,因此请确保您没有在 spring 上下文之外实例化事物。

这是一个模拟服务器的简单示例,用于获取一些帖子:

@RunWith(SpringRunner.class)
@RestClientTest(PostClient.class)
public class PostClientMockTest {
// class under test
@Autowired
private PostClient postClient;
// autowired mock server from the spring context
@Autowired
private MockRestServiceServer mockRestServiceServer;
@Test
public void readPosts() throws Exception {
String mockJsonResponse = "My response";
mockRestServiceServer.expect(requestTo("https://myurl.com/posts?userId=1"))
.andRespond(withSuccess(mockJsonResponse, MediaType.APPLICATION_JSON_UTF8));
List<Post> posts = postClient.readPosts(1);
assertEquals(9, posts.size());
mockRestServiceServer.verify();
}
}

希望这有帮助

最新更新