【问题标题】:Spring doesn't autowire fields when runner invokes '@Before' method当运行器调用“@Before”方法时,Spring 不会自动装配字段
【发布时间】:2023-03-25 13:44:01
【问题描述】:

我有以下测试:

@RunWith(Parameterized.class)
@SpringBootTest
@ContextConfiguration(classes = MyConfig.class)
public class OrderPlacementCancelTest {
    @Autowired
    private TestSessionsHolderPerf sessionsHolder;

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    private CommonCredentialSetter commonCredentialSetter;

    @Before
    public void login() throws InterruptedException {        
        int attempts = 0;
        while (!sessionsHolder.isClientLoggedIn() && attempts < 3) {
            Thread.sleep(1000);
            ++attempts;
        }

    }
     @Parameterized.Parameters()
     public static Collection<Object[]> data() {
        ...
     }

和以下跑步者:

@Test
    public void test() throws Exception {
        Class[] cls = {OrderPlacementCancelTest.class};
        Result result = JUnitCore.runClasses(new ParallelComputer(false, true), cls);
        logger.info("Failure count={}", result.getFailureCount());
        for (Failure failure : result.getFailures()) {
            logger.error(failure.getTrace());
        }
    }

当我通过 runner 开始测试时,我看到 sometimes 方法 login 标记为 @Before 抛出 NullPointerException 因为 sessionHolder 为空。

如何避免?

【问题讨论】:

  • 可能与混入@Parameterized 有关。也许使用TestContextManager 来初始化类可以避免这个问题。 stackoverflow.com/a/3522237/3280538
  • @flakes 你是对的,请添加答案,我会接受

标签: java junit concurrency spring-test junit-toolbox


【解决方案1】:

@Parameterized 似乎与 junit 规则不能很好地融合。一种选择是通过在参数化测试类的构造函数中执行逻辑来替换Rule,或者在测试方法的开头调用设置方法。

在任何一种情况下,您都可以使用 TestContextManager 使用 @AutoWired 值填充您的测试类,如下所示:

private TestContextManager testContextManager;

@Before
public void login() throws Exception {
    testContextManager = new TestContextManager(getClass());
    testContextManager.prepareTestInstance(this);

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2014-09-07
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    相关资源
    最近更新 更多