问题描述
当我在JUnit中编写测试时(在Spring上下文中)我通常这样做:
When I write tests in JUnit (in Spring context) I usualy do it like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:testContext.xml")
public class SimpleTest {
@Test
public void testMethod() {
// execute test logic...
}
}
我该怎么办和TestNG一样吗?
How can I do the same with TestNG?
我会添加更多细节。使用AbstractTestNGSpringContextTests它可以工作,但不是我想要的方式。
我有一些测试......
I'll add more details. With AbstractTestNGSpringContextTests it works, but not in a way I want to.I have some test ...
@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)
这就是我询问跑步者的原因。
推荐答案
正确,TestNG总是实例化Test类(在构造函数中放置断点来验证)。稍后(@BeforeClass)将上下文中的bean注入Test类。
Correct, TestNG always instantiates the Test class (put breakpoint in constructor to verify). Later (@BeforeClass) the beans from the context is injected into the Test class.
但我很好奇为什么你们首先将测试定义为bean。在我使用Spring的10年里,我从来没有这么做过,或者看过有人这样做过......
I'm however curious as to why you would every define the test as a bean in the first place. In the 10 years I have used Spring I have never needed to do that, or seen anyone do it...
这篇关于TestNG是否有像SpringJUnit4ClassRunner这样的跑步者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!