使用带有jUnit5和SpringBoot的随机端口进行协议测试

时间:2018-12-20 15:03:48

标签: spring-boot testing junit5 pact

使用jUnit5时,无法让pact提供程序测试在8080以外的任何其他端口上运行。我有以下代码:

@ExtendWith(SpringExtension.class)
@Provider(PROVIDER)
@PactFolder("pacts")
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class PactProviderTest {

  @LocalServerPort private int serverPort;

  @Autowired Result<IServiceManagementFacade2> serviceManagementFacade;

  @Autowired private RestServiceFactory restServiceFactory;

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void pactVerificationTestTemplate(PactVerificationContext context) {
    context.setTarget(new HttpTestTarget("localhost", serverPort));
    context.verifyInteraction();
  }

运行此命令时,出现以下错误:

Request Failed - Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)

如果我更改

  

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

  

@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)

测试通过。但是,在测试期间,该端口上将无法运行其他应用程序,这在测试环境中是不可接受的。有什么想法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我设法解决了。

移动线:

context.setTarget(new HttpTestTarget(“ localhost”,serverPort));

@BeforeEach解决了该问题。之所以不起作用,是因为我使用了变量来设置它。

所以要做这样的事情:

  @LocalServerPort private int serverPort;
  private HttpTestTarget target = new HttpTestTarget("localhost", serverPort);

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void pactVerificationTestTemplate(PactVerificationContext context) {
    context.verifyInteraction();
  }

  @BeforeEach
  void setTarget(PactVerificationContext context) {
    context.setTarget(target);
  }

不起作用。

这确实起作用:

  @LocalServerPort private int serverPort;

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void pactVerificationTestTemplate(PactVerificationContext context) {
    context.verifyInteraction();
  }

  @BeforeEach
  void setTarget(PactVerificationContext context) {
    context.setTarget(new HttpTestTarget("localhost", serverPort));
  }