赞
踩
JUnit是一个Java语言的单元测试框架。可以给出成功的测试和失败的测试,还可以生成测试报告,不仅可以统计测试的成功率,还可以统计测试的代码覆盖率,对于高质量的代码,测试覆盖概率要在80%以上。
针对最小功能单元编写测试代码;java中最小功能单元是方法,Java单元测试针对的是方法的测试
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
ssertEquals :验证是否相等
assertTrue:期待结果为true
assertFalse:期待结果为false
assertNotNull:期待结果非null
assertArrayEquals:期待结果为数组,并且每个元素的值均相等
…
运行代码:
package junit;
import org.junit.jupiter.api.Test;
public class JunitTest {
private long n =0;
public long add(long x){
n=n+x;
return n;
}
public long sub (long x){
n=n-x;
return n;
}
}
测试代码:
package junit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class FachTest { JunitTest junitTest; @BeforeEach public void setup(){ this.junitTest= new JunitTest(); } @AfterEach public void tearDown(){ this.junitTest=null; } @Test void setJunitTest(){ Assertions.assertEquals(100,this.junitTest.add(100)); Assertions.assertEquals(200,this.junitTest.add(100)); Assertions.assertEquals(150,this.junitTest.sub(50)); } @Test void getJunitTest(){ Assertions.assertEquals(-100,this.junitTest.sub(100)) ; Assertions.assertEquals(-150,this.junitTest.sub(50)) ; Assertions.assertEquals(-130, this.junitTest.sub(-20)); } }
package junit; public class MessageUtil { private String message; MessageUtil(String message){ this.message = message; } // 打印message public String printMessage(){ System.out.println("MessageUtil类中printMessage()方法中的输出信息:"+message); int a=0; int b = 1/a; return message; } // 打印添加内容后的message public String salutationMessage(){ message = "Add"+message; System.out.println("MessageUtil类中salutationMessage()方法中的输出信息:"+message); return message; } }
package junit; import org.junit.jupiter.api.Test; public class TestJunit { String message = "测试信息"; MessageUtil messageUtil = new MessageUtil(message); @Test(expected = ArithmeticException.class) public void testPrintMessage() { System.out.println("对PrintMessage()方法返回的值进行测试"); assertEquals(message,messageUtil.printMessage()); } @Test public void testsalutationMessage(){ System.out.println("对salutationMessage()方法返回的值进行测试"); message = "Add"+message; assertEquals(message,messageUtil.salutationMessage()); } }
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for(Failure failure:result.getFailures()){
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。