java没有TestNG有SpringJUnit4ClassRunner这样的runner
当我在JUnit(在Spring环境中)中编写测试时,我通常是这样做的:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:testContext.xml")
public class SimpleTest {
@Test
public void testMethod() {
// execute test logic...
}
}
如何使用TestNG实现同样的功能
我会补充更多细节。使用AbstractTestNGSpringContextTests,它可以工作,但不是以我想要的方式。 我有一些测试
@ContextConfiguration(locations = { "classpath:applicationContextForTests.xml" })
public class ExampleTest extends AbstractTestNGSpringContextTests {
private Boolean someField;
@Autowired
private Boolean someBoolean;
@Test
public void testMethod() {
System.out.println(someField);
Assert.assertTrue(someField);
}
@Test
public void testMethodWithInjected() {
System.out.println(someBoolean);
Assert.assertTrue(someBoolean);
}
// setters&getters
}
还有描述符
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="exampleTest" class="pl.michalmech.ExampleTest">
<property name="someField">
<ref bean="someBoolean"/>
</property>
</bean>
<bean id="someBoolean" class="java.lang.Boolean">
<constructor-arg type="java.lang.String" value="true"/>
</bean>
</beans>
结果是
null
true
Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.599 sec <<< FAILURE!
Results :
Failed tests:
testMethod(pl.michalmech.ExampleTest)
这就是为什么我问《跑步者》
# 1 楼答案
TestNG不使用Spring来实例化测试。这就是为什么someField=null
# 2 楼答案
正确,TestNG总是实例化测试类(将断点放在构造函数中进行验证)。稍后(@BeforeClass)将上下文中的bean注入测试类
然而,我很好奇,为什么你一开始就把测试定义为一个bean。在我使用Spring的10年里,我从来没有这样做过,也没有见过有人这样做过