</pre>在开发过程中,会建许多类,并且在类中创建许多处理方法,怎么保证写的方法正确并达到自己想要的效果呢?也许有人说写个main方法测试下,但是我有N个方法呢?那么要写N个main方法咯,那这样就太麻烦了,由此,我们可以用单元测试来解决这个问题<p></p><p></p><p>创建单元测试步骤:</p><p></p><p>1.新建一个类,并写几个方法</p><p><pre name="code" class="java">public class Math {
public int add(int x, int y) {
return x + y;
}
public int substraction(int x, int y) {
return x - y;
}
public int multiplication(int x, int y) {
return x * y;
}
public int division(int x, int y) {
return x / y;
}
public String split(){
StringBuffer sb = new StringBuffer();
sb.append("hello");
sb.append('-');
sb.append("world");
return sb.toString();
}
}
2.新建一个单元测试用例
public class MathTest {
@Before
public void before(){
System.out.println("before");
}
@After
public void after(){
System.out.println("after");
}
@Test
public void testAdd() {
// fail("尚未实现");
int z = new Math().add(2, 5);
assertEquals(z, 7);
}
@Test(timeout=100)
public void testSubstraction() {
// fail("尚未实现");
int z = new Math().substraction(5, 2);
assertEquals(z, 3);
}
@Test
public void testMultiplication() {
// fail("尚未实现");
int z = new Math().multiplication(3, 5);
assertEquals(z, 15);
}
@Test
public void testDivision() {
// fail("尚未实现");
int z = new Math().division(9, 3);
assertEquals(z, 3);
}
@Test
public void testSplit(){
String z = new Math().split();
assertEquals(z,"hello-world");
//assertThat(z, is("fasdfds"));
}
3.选中测试用例的类名,右键选中运行方式为JUnit测试,就能看到测试结果了
failuer代表测试失败;error代表程序错误