简体   繁体   English

为什么我的集成测试试图设置一个新的码头实例?

[英]Why is my Integration Test trying to setup a new jetty instance?

I have a project with 3 integration tests classes: A, B and C. I made a change in the code, and as part of those changes I added a @MockBean to test class A.我有一个包含 3 个集成测试类的项目:A、B 和 C。我对代码进行了更改,作为这些更改的一部分,我添加了一个 @MockBean 来测试类 A。

Here is a class that is extended by every Integration Test class:这是一个由每个集成测试类扩展的类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class, webEnvironment = RANDOM_PORT)
@TestPropertySource(locations = "classpath:application-test.yml")
@ActiveProfiles(profiles = {"default", "test"})
public abstract class IntegrationTest {

    @Value("${local.server.port}")
    private int serverPort;

    @Autowired
    private ObjectMapper objectMapper;

    @Before
    public void setUpIntegrationTest() {
        RestAssured.port = serverPort;
        RestAssured.config = RestAssuredConfig.config()
                .logConfig(LogConfig.logConfig()
                        .enableLoggingOfRequestAndResponseIfValidationFails()
                        .enablePrettyPrinting(true))
                .objectMapperConfig(objectMapperConfig()
                        .jackson2ObjectMapperFactory((cls, charset) -> objectMapper)
                        .defaultObjectMapperType(ObjectMapperType.JACKSON_2))
                .jsonConfig(jsonConfig().numberReturnType(BIG_DECIMAL))
                .redirect(new RedirectConfig().followRedirects(false));
    }
}

Now for a concrete test class:现在是一个具体的测试类:

import org.springframework.boot.test.mock.mockito.MockBean;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;

public class TestClassA extends IntegrationTest {
    @MockBean
    private SomeBean foo;

    @Before
    @Override
    public void setUpIntegrationTest() {
        super.setUpIntegrationTest();
        doNothing().when(foo).fooMethod(any(SomeClass.class), any(SomeOtherClass.class));
    }

    @Test
    public void testCaseX() {
        given()
            .body("{\"foo\": \"bar\"}")
        .when()
            .post("/some/path/")
        .then()
            .statusCode(OK.value());
    }
}

I have tried to run tests in three different ways:我尝试以三种不同的方式运行测试:

  1. Run only test class A, with the mocked bean.仅使用模拟 bean 运行测试类 A。 All tests pass.所有测试都通过。
  2. Build the project which runs all test classes.构建运行所有测试类的项目。 Test classes B and C pass, but A fails during application context loading while trying to start a jetty instance and fails because the address is already in use.测试类 B 和 C 通过,但 A 在尝试启动 jetty 实例时在应用程序上下文加载期间失败,并且由于地址已被使用而失败。

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.github.azagniotov.stubby4j.server.StubbyManager]: Factory method 'stubby' threw exception;引起:org.springframework.beans.BeanInstantiationException:无法实例化[io.github.azagniotov.stubby4j.server.StubbyManager]:工厂方法'stubby'抛出异常; nested exception is java.net.BindException: Address already in use Caused by: java.net.BindException: Address already in use嵌套异常是 java.net.BindException: Address already in use 导致:java.net.BindException: Address already in use

  1. Remove the mocked bean, and build the project.删除模拟 bean,然后构建项目。 Test classes B and C pass.测试班级 B 和 C 通过。 Test class A successfully loads the application context, but some tests fail (due to the missing behaviour given by the mock).测试类 A 成功加载应用程序上下文,但某些测试失败(由于模拟给出的行为缺失)。

Jetty is setup as part of Stubby4j and it is instantiated as a configuration bean in the following way: Jetty 被设置为Stubby4j 的一部分,并通过以下方式实例化为配置 bean:

@Configuration
public class StubbyConfig {

    @Bean
    public StubbyManager stubby(final ResourceLoader resourceLoader) throws Exception {

        Resource stubbyFile = resourceLoader.getResource("classpath:stubs/stubby.yml");

        if (stubbyFile.exists()) {
            Map<String, String> stubbyConfig = Maps.newHashMap();
            stubbyConfig.put("disable_admin_portal", null);
            stubbyConfig.put("disable_ssl", null);

            File configFile = stubbyFile.getFile();
            Future<List<StubHttpLifecycle>> stubLoadComputation =
                    ConcurrentUtils.constantFuture(new YAMLParser().parse(configFile.getParent(), configFile));

            StubbyManager stubbyManager = new StubbyManagerFactory()
                    .construct(configFile, stubbyConfig, stubLoadComputation);
            stubbyManager.startJetty();

            return stubbyManager;
        } else {
            throw new FileNotFoundException("Could not load stubby.yml");
        }
    }
}

I did some debugging in two different ways, putting a break point in the line stubbyManager.startJetty();我以两种不同的方式进行了一些调试,在stubbyManager.startJetty();行中放置了一个断点stubbyManager.startJetty(); :

  1. Running just test class A. Execution stopped in the break point only once.仅运行测试类 A。执行仅在断点处停止一次。
  2. Running test class A with some other test class (for example, B).使用其他测试类(例如 B)运行测试类 A。 Execution stopped only once for B, but twice for A. The second time it failed with the aforementioned error. B 的执行只停止了一次,但 A 的执行停止了两次。第二次它因上述错误而失败。
  3. Again, if I remove the mocked bean and run multiple test classes the execution only stops at that line once per test class.同样,如果我删除模拟 bean 并运行多个测试类,则每个测试类的执行只会在该行停止一次。

My question, obviously, is: why does the MockedBean annotation cause this behaviour, and how can I avoid it?显然,我的问题是:为什么 MockedBean 注释会导致这种行为,我该如何避免?

Thanks in advance.提前致谢。

Current project setup:当前项目设置:

  • Spring Boot version 1.4.2.RELEASE Spring Boot 版本 1.4.2.RELEASE
  • Stubby4j version 4.0.4 Stubby4j 版本 4.0.4

I just start Jetty when not already done with:我只是在尚未完成时启动 Jetty:

if(!stubbyManager.statuses().contains(""Stubs portal configured at")
    stubbyManager.startJetty();
else
    stubbyManager.joinJetty();

Let me know if you find a better solution如果您找到更好的解决方案,请告诉我

You could use Spring's SocketUtils class to find available TCP port, which then you could pass into your stubbyConfig map:您可以使用 Spring 的SocketUtils类来查找可用的 TCP 端口,然后您可以将其传递到您的 stubbyConfig 映射中:

...
static final int PORT_RANGE_MIN = 2048;
static final int PORT_RANGE_MAX = 65535;
...
...
public StubbyConfig() {
  this.stubPort = SocketUtils.findAvailableTcpPort(PORT_RANGE_MIN, PORT_RANGE_MAX);
}
...
@Bean
public StubbyManager stubby(final ResourceLoader resourceLoader) throws Exception {
    ...
    if (stubbyFile.exists()) {
       ...
       stubbyConfig.put("stubs", String.valueOf(stubsPort));
       ...
    }
}
...
public int getStubsPort() {
  return this.stubPort;
}

Then, because you have the port getter on your StubbyConfig class, you could pass it to the RestAssured.port when running the integration test然后,因为您的 StubbyConfig 类上有端口 getter,所以您可以在运行集成测试时将其传递给RestAssured.port

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM