【java】单元测试(一)
视频请看我的公众号,第一次录制小视频,希望大家多多给意见。
什么是单元测试?
单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证。比如我们可以测试一个类,或者一个类中的一个方法。
单元测试有什么好处请看一下百度百科中归纳的四条:
1、它是一种验证行为。
程序中的每一项功能都是测试来验证它的正确性。它为以后的开发提供支援。就算是开发后期,我们也可以轻松的增加功能或更改程序结构,而不用担心这个过程中会破坏重要的东西。而且它为代码的重构提供了保障。这样,我们就可以更自由的对程序进行改进。
2、它是一种设计行为。
编写单元测试将使我们从调用者观察、思考。特别是先写测试(test-first),迫使我们把程序设计成易于调用和可测试的,即迫使我们解除软件中的耦合。
3、它是一种编写文档的行为。
单元测试是一种无价的文档,它是展示函数或类如何使用的最佳文档。这份文档是可编译、可运行的,并且它保持最新,永远与代码同步。
4、它具有回归性。
自动化的单元测试避免了代码出现回归,编写完成之后,可以随时随地的快速运行测试。
贴两段代码吧。
package com.testdev.unittestdemo;
public class Calculator {
public int add(int a, int b){
return a + b;
}
public int subtraction(int a, int b){
return a - b;
}
public int multiply(int a, int b){
return a * b;
}
public int divide(int a, int b) throws Exception{
if(0 == b){
throw new Exception("除数不能为0");
}
return a / b;
}
}
测试代码:
单元测试框架:testng
package com.testdev.unittestdemo;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class CalculatorTest {
Calculator calculator;
@org.testng.annotations.BeforeMethod
public void setUp() throws Exception {
calculator = new Calculator();
}
@org.testng.annotations.AfterMethod
public void tearDown() throws Exception {
}
@Test
public void test_add_1_2(){
int addres = calculator.add(1,2);
assertEquals(3,addres);
}
@Test
public void test_sub_1_2(){
int subres = calculator.subtraction(1,2);
assertEquals(-1,subres);
}
@Test
public void test_mul_1_2(){
int mulres = calculator.multiply(1,2);
assertEquals(2,mulres);
}
@Test
public void test_div_1_0() throws Exception{
int divres = calculator.divide(1,0);
assertEquals(0,divres);
}
}
更多精彩内容