junit学习笔记

用实例说话:对HelleWord进行测试

package com.cathay.saga;

public class HelleWord {

public String sayHello(){
return "Hello World";
}

public String sayHello2(){
return "Hello World2";
}

}

junit测试代码:
package com.cathay.saga;

import junit.framework.TestCase;
import junit.textui.TestRunner;

public class HelloWorldTest extends TestCase{
         //测试前搭建环境
protected void setUp(){

}
//释放资源
protected void tearDown(){

}

public void testSayHello2(){
HelleWord w=new HelleWord();
assertEquals("Hello World2", w.sayHello2());
}

public void testSayHello(){
HelleWord w=new HelleWord();
assertEquals("Hello World", w.sayHello());
}

public static void main(String[] args) {
TestRunner.run(HelloWorldTest.class);
}
}

执行main方法,控制台打印:
Time: 0

OK (2 tests)
测试通过,assertEquals(XXX,XXX)返回true,反之测试不通过,打印错误信息

对多个TestCase集合测试:
package com.cathay.saga;

import junit.framework.Test;
import junit.framework.TestSuite;

public class AllTests {

public static Test suite() {
TestSuite suite = new TestSuite("Test for com.cathay.saga");
//$JUnit-BEGIN$
suite.addTestSuite(HelloWorldTest.class);
suite.addTestSuite(SimpleTest.class);
//$JUnit-END$
return suite;

}

}

SimpleTest代码如下:
package com.cathay.saga;

import junit.framework.TestCase;
import junit.textui.TestRunner;

public class SimpleTest extends TestCase {

public SimpleTest(String name){
super(name);
}

public void testTest(){
assertTrue(true);
}

public static void main(String[] args) {
TestRunner.run(SimpleTest.class);
}
}

总结:项目测试中,搭建统一的测试环境,setUp()中调用,测试完毕tearDown()释放资源。测试数据的准备是测试效果是否达到的关键所在。

你可能感兴趣的:(JUnit)