@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class, loader = AnnotationConfigContextLoader.class)
@TestExecutionListeners(listeners = LoadBalancingIntegrationTest.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
public class LoadBalancingIntegrationTest extends AbstractTestExecutionListener{

    //...

    DummyWebAppService[] dummyWebAppControllers = new DummyWebAppService[4];

    int haproxyListeningPort = 8000;

    //DummyWebApp
    @Value("${dummyWebApp.mvnPath}")
    String mavenPath;

    @Value("${dummyWebApp.webAppPath}")
    String webAppPath;

    @Override
    public void beforeTestClass(TestContext testContext) throws Exception {
        dummyWebAppControllers[0] = new DummyWebAppService(mavenPath, webAppPath, 8080);
    }

    //..test cases follow
}


我在测试用例中使用spring依赖注入。我对TestExecutionListeners的执行顺序有疑问。根据this documentation about the ordering of custom TestExecutionListeners,可以通过Ordered接口或@Order批注以及by default, the order is of lowest predence for any custom TestExecutionListener指定订单。但是,执行此测试类时,在任何注入之前执行beforeTestClass。我什至放了mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS,所以不会遗漏默认的TestExecutionListeners。当注释出beforeTestClass时,注入照常执行。

我的问题是,为什么先执行我的beforeTestClass?我可以告诉它在注射后执行吗?

最佳答案

不知道这是否是正确的解决方案,但是对于我的用例来说已经足够了,该用例是在beforeTestClass之前注入bean。只需通过编写即可强制其自动接线
@Override public void beforeTestClass(TestContext testContext) throws Exception { testContext.getApplicationContext().getAutowireCapableBeanFactory().autowireBean(this); dummyWebAppControllers[0] = new DummyWebAppService(mavenPath, webAppPath, 8080); }

似乎有点强迫自动接线,但是我的问题解决了

09-07 14:34