我有以下测试:
@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());
}
}
当我通过跑步者开始测试时,我发现有时标记为login
的方法@Before
会抛出NullPointerException
因为sessionsHolder为null。
我怎么能避免呢?
似乎@Parameterized
与junit规则不能很好地融合。一种选择是通过在参数化测试类的构造函数中执行逻辑来替换Rule
,或者在测试方法的开头调用setup方法。
在任何一种情况下,您都可以使用TestContextManager
使用@AutoWired
值填充您的测试类,如下所示:
private TestContextManager testContextManager;
@Before
public void login() throws Exception {
testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);