JUnit单元测试基础

来源:互联网 发布:淘宝助理怎样下载宝贝 编辑:程序博客网 时间:2024/05/20 10:14

</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 {   @Beforepublic void before(){System.out.println("before");}@Afterpublic void after(){System.out.println("after");}@Testpublic 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);}@Testpublic void testMultiplication() {// fail("尚未实现");int z = new Math().multiplication(3, 5);assertEquals(z, 15);}@Testpublic void testDivision() {// fail("尚未实现");int z = new Math().division(9, 3);assertEquals(z, 3);}@Testpublic void testSplit(){String z = new Math().split();assertEquals(z,"hello-world");//assertThat(z, is("fasdfds"));}

3.选中测试用例的类名,右键选中运行方式为JUnit测试,就能看到测试结果了
failuer代表测试失败;error代表程序错误
0 0
原创粉丝点击