由于实在不会使用C语言的单元测试工具CUnit,因此自己又学习了JUnit的使用,并建立了一个小项目,实战了一下。
GitHub:https://github.com/Max577769190/test/tree/master/Work_2
import static org.junit.Assert.*; import org.junit.Test; public class FirstDayAtSchoolTest { FirstDayAtSchool school = new FirstDayAtSchool(); String[] bag1 = { "Books", "Notebooks", "Pens" }; String[] bag2 = { "Books", "Notebooks", "Pens", "Pencils" }; @Test public void testPrepareMyBag() { System.out.println("Inside testPrepareMyBag()"); assertArrayEquals(bag1, school.prepareMyBag()); } @Test public void testAddPencils() { System.out.println("Inside testAddPencils()"); assertArrayEquals(bag2, school.addPencils()); } }
测试运行结果
PrepareMyBagTest.java
import org.junit.Test; import static org.junit.Assert.*; public class PrepareMyBagTest { FirstDayAtSchool school = new FirstDayAtSchool(); String[] bag = { "Books", "Notebooks", "Pens" }; @Test public void testPrepareMyBag() { System.out.println("Inside testPrepareMyBag()"); assertArrayEquals(bag, school.prepareMyBag()); } }
AddPencilsTest.java
import org.junit.Test; import static org.junit.Assert.*; public class AddPencilsTest { FirstDayAtSchool school = new FirstDayAtSchool(); String[] bag = { "Books", "Notebooks", "Pens", "Pencils" }; @Test public void testAddPencils() { System.out.println("Inside testAddPencils()"); assertArrayEquals(bag, school.addPencils()); } }
使用套件测试,RunWith.java
import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ PrepareMyBagTest.class, AddPencilsTest.class }) public class SuiteTest { }
测试运行结果
Parameterized
是JUnit一个执行类,可以根据不同的输入运行相同的测试用例。Calculate.java
public class Calculate { public int sum(int var1, int var2) { System.out.println("Adding values: " + var1 + " + " + var2); return var1 + var2; } }
CalculateTest.java
import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class CalculateTest { private int expected; private int first; private int second; public CalculateTest(int expectedResult, int firstNumber, int secondNumber) { this.expected = expectedResult; this.first = firstNumber; this.second = secondNumber; } @Parameters public static Collection addedNumbers() { return Arrays.asList(new Integer[][] { { 3, 1, 2 }, { 5, 2, 3 }, { 7, 3, 4 }, { 9, 4, 5 }, }); } @Test public void sum() { Calculate add = new Calculate(); System.out.println("Addition with parameters : " + first + " and " + second); assertEquals(expected, add.sum(first, second)); } }
测试运行结果