1. 在pom.xml中添加testng引用:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.4</version>
</dependency>
2. 测试基类,构筑testng的spring上下文:
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.testng.annotations.Test;
@ContextConfiguration(locations={"classpath:conf/spring/spring-impl.xml"})
@TransactionConfiguration(defaultRollback = true)
public abstract class BaseTest extends AbstractTestNGSpringContextTests {
@Test
public void test() {
System.out.println("I'm basic test");
}
}
3. 测试类:
public class PerturbServiceTest extends BaseTest {
@Resource
PerturbService perturbService;
@Test
public void perturbTest() throws Exception {
String accountNo = "5201314";
PerturbDto dto = new PerturbDto();
dto.setAccountNo(accountNo);
perturbService.perturb(dto);
}
}
4. 执行测试:
a. 选中perturbTest,右键[Run As] ([Debug As]) [TestNG Test]。
b. 首先,新建测试文件testng.perturbServiceTest.xml:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="PerturbServiceTest" verbose="1">
<test name="PerturbServiceTest">
<classes>
<class name="com.john.common.service.impl.PerturbServiceTest">
<methods>
<include name="perturbTest" />
</methods>
</class>
</classes>
</test>
</suite>
如果仅仅是执行该测试,在Eclipse视图[Package Explorer]上右键该文件,然后[Run As] ([Debug As]) [TestNG Suite],即可进行测试。
如果需要测试多个类,在testng.xml文件中添加此XML文件的路径:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="common-service" verbose="1">
<suite-file path="../common-service/src/test/testng.counselServiceTest.xml" />
<suite-file path="../common-service/src/test/testng.perturbServiceTest.xml" />
</suite-files>
</suite>
测试方法同上。