单元测试是开发中必不可少的一部分,是产品代码的重要保证。
Junit和testNG是当前最流行的测试框架,Junit是使用最广泛的测试框架,有兴趣的话自己baidu一下。
testNG基于Junit和Nunit,并引入了很多特性,使其更强大和更易于使用。
有兴趣的可以直接看一下官网:http://testng.org/doc/index.html
用maven可以很方便的构建测试框架。
在这里以maven为例搭建一个测试框架
编辑pom.xml引入必要的jar包
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<powermock.version>1.6.3</powermock.version>
<cobertura.version>2.1.1</cobertura.version>
<sonar.version>5.1</sonar.version>
<junit.version>4.12</junit.version>
</properties> <dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.cobertura</groupId>
<artifactId>cobertura</artifactId>
<version>${cobertura.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar-plugin-api</artifactId>
<version>${sonar.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
基本的框架已经搭建,下面写一个最简单的测试类
很多例子取自<<PowerMock实战手册>><<Instant Mock Testing with PowerMock>>
http://wenku.baidu.com/link?url=hKW9B15IRoqIrjpWKYDeR_cGL9hRgYvbT7-rbds59i19l70qzGeW7x3Tzr24Vwuq-vWHggOq6XOs_saW33Li7E492UlXWM8JIpyKMyhvhwa
待测试类:
public class EmployeeService { public String hello(){
return "Hello word!";
}
}
测试类:
public class EmployeeServiceTest {
@Test
public void hello(){
Assert.assertEquals(employeeService.hello(), "Hello word!");
}
}
这是一个不能再简单的例子了,如果IDE有testNG插件的话,直接右键EmployeeServiceTest→run as→testNG test就可以运行。
结果如下:
[TestNG] Running:
C:\Users\changzhz\AppData\Local\Temp\testng-eclipse--447685701\testng-customsuite.xml PASSED: hello ===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
=============================================== ===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
=============================================== [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@5f205aa: 344 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@424c0bc4: 47 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@2ff5659e: 196 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@1996cd68: 4 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@27ddd392: 13 ms
或者用maven运行 :mvn clean test
用maven调用时,请确保测试类以Test或testCase结尾
这个例子太简单了,只是简单说明怎么构架,怎么运行。