单元测试利器JUnit的实践与总结
单元测试工具Junit是一个开源项目,昨天学习了一下这个东西,总结下心得。
1.创建相应的test类

package:测试类存放位置。
Name:测试类名字。
setUp,tearDown:测试类创建测试环境以及销毁测试环境,这两个方法只执行一次。
Class Under test:需要被测试的类路径及名称。
点击下一步就会让你选择需要给哪些方法进行测试。
测试类创建完成后在类中会出现你选择的方法的测试方法:
package test.com.boco.bomc.alarmrelevance.show.dao;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class ShowStrategyDaoTest extends TestCase{
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("OK1");
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public final void testGetDataByApplyNameOrHostIp() {
fail("Not yet implemented"); // TODO
}
@Test
public final void testGetDataByObject() {
fail("Not yet implemented"); // TODO
}
@Test(timeout=1)
public final void testGetApplyUser() {
fail("Not yet implemented"); // TODO
}
@Test
public final void testGetVoiceUser() {
fail("Not yet implemented"); // TODO
}
@Test
public final void testSearchInAera() {
fail("Not yet implemented"); // TODO
}
@Test
public final void testGetDataByPolicyId() {
fail("Not yet implemented"); // TODO
}
} 其中的@before,@test,@after表示在执行测试方法前执行,需执行的测试方法,在测试方法执行后执行。
可以给@test添加timeout,exception参数。
在测试方法中可以用assertEquals(arg0,arg1);
可以用TestSuite把多个测试类集中到一起,统一执行测试,例如:
package test.com.boco.bomc.alarmrelevance.show.dao;
import junit.framework.Test;
import junit.framework.TestSuite;
public class TestAll {
public static Test suite(){
TestSuite suite = new TestSuite("Running all the tests");
suite.addTestSuite(ShowStrategyDaoTest.class);
suite.addTestSuite(com.boco.bomc.alarmrelevance.show.dao.ShowStrategyDaoTest.class);
return suite;
}
} 另外还可以把多个TestSuite组合到一个Test类里面,例如:
package test.com.boco.bomc.alarmrelevance.show.dao;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class TestAll1 extends TestCase {
public static Test suite(){
TestSuite suite1 = new TestSuite("TestAll1");
suite1.addTest(TestAll.suite());
suite1.addTest(TestAll2.suite());
return suite1;
}
} 这就更方便与集中测试,一个方法测试完了,可以对个方法,多个类一起测试。
注意:在写代码的时候TestSuite,TestCase,Test的包不要到错了。
测试效果如下:

相关推荐
lustdevil 2020-08-03
zhengzf0 2020-06-21
宿命java 2020-06-15
snowphy 2020-06-06
Julywhj 2020-05-26
AnndyR 2020-05-15
snowphy 2020-05-12
shirleypaddy 2020-10-19
qingmumu 2020-10-19
lustdevil 2020-10-18
ganlulululu 2020-10-12
lustdevil 2020-07-18
lustdevil 2020-06-25
lustdevil 2020-06-21
JackYin 2020-06-14
dongxurr 2020-06-07