问题描述
我进行了以下测试:
@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());
}
}
当我通过跑步者开始测试时,我看到有时标记为@Before
的方法login
会抛出NullPointerException
,因为sessionsHolder为空.
When I start test via runner I see that sometimes method login
marked as @Before
throws NullPointerException
because sessionsHolder is null.
如何避免呢?
推荐答案
似乎@Parameterized
与junit规则不能很好地融合在一起.一种选择是通过在参数化测试类的构造函数中执行逻辑来替换Rule
,或者在测试方法的开头调用setup方法.
It seems that @Parameterized
does not mix well with junit rules. One option would be to replace the Rule
by performing the logic in the constructor of the parameterized test class, or calling a setup method at the beginning of your test methods.
在任何一种情况下,您都可以使用TestContextManager
像这样用@AutoWired
值填充测试类:
In either case you can use TestContextManager
to populate your test class with the @AutoWired
values like this:
private TestContextManager testContextManager;
@Before
public void login() throws Exception {
testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
这篇关于当跑步者调用'@Before'方法时,Spring不会自动关联字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!