搞定Junit单元测试{非专业}

1:测试分类

2:常用测试方法

2.1 断言语句

3: 基本测试

4: 组合测试

5:参数化测试

6:分类测试(Category)

1:测试分类

  •   1. 黑盒测试:不需要写代码,给输入值,看程序是否能够输出期望的值。
  •   2. 白盒测试:需要写代码的。关注程序具体的执行流程。

2:常用测试方法

Junit 组合测试注解:

  •   RunWith      指定测试类的为指定容器 可以为 Category SuitCase
  •  Parametered  建立参数类 且必须提供一个内部的静态方法 返回一个集合的Collection<Object[]>
  •  Runwith 必须是Parameterized.class
  •   Category 将测试方法 分类
  •  RunWith 必须指定为Categories.class
  •  FixMethodOrder  定义测试次序

 2.1 断言语句

                 Assert 以静态方法 提供了一系列的测试方法

Method

Description

assertNull(java.lang.Object object)

检查对象是否为空

assertNotNull(java.lang.Object object)

检查对象是否不为空

assertEquals(long expected, long actual)

检查long类型的值是否相等

assertEquals(double expected, double actual, double delta)

检查指定精度的double值是否相等

assertFalse(boolean condition)

检查条件是否为假

assertTrue(boolean condition)

检查条件是否为真

assertSame(java.lang.Object expected, java.lang.Object actual)

检查两个对象引用是否引用同一对象(即对象是否相等)

assertNotSame(java.lang.Object unexpected, java.lang.Object actual)

检查两个对象引用是否不引用统一对象(即对象不等)

Fail()

 直接返回一个测试失败的方法

  3: 基本测试

public class Usually_Test {
    private int a;
    private int b;
    @BeforeClass
    public static  void start() {
        System.out.println("start--------");
    }
    @Before
    public void before() {
        this.a=4;
        this.b=5;
    }
    @Test
    public void testAdd() {
        int res=add(a, b);
        assertEquals(9, res);
    }
    @Ignore
    public void testAdd2() {
        int res=add(a, b);
        assertEquals(9, res);
        System.out.println("testAdd2方法被忽略");
    }
    public static int add(int a,int b) {
        return a+b;
    }
    @After
    public void after() {
        this.a=0;
        this.b=0;
    }
    @AfterClass
    public static void end() {
        System.out.println("end-----------");
    }
}

  

4: 组合测试

@RunWith(Suite.class)  //标示为组合测试
@SuiteClasses({A.class,B.class}) // 被测试的类必须为public类
public class ALLTest {
    // all test
}
public class A{
    @Test
    public void test_m() {
        
    }
}
public class B{
    @Test
    public void test_m() {
        
    }
}

5:参数化测试

必须提供@Parameter方法,方法的返回必须是public static Collection,不能有参数,

并且collection元素必须是相同长度的数组。同时数组的长度必须与测试类的字段(m1,m2,result)的数量相匹配

  •  参数字段必须是public
@RunWith(Parameterized.class) // 必须指定为Parameterized.class
public class ParameterizedTestFields {
    @Parameterized.Parameter(0)
    public int a;
    @Parameterized.Parameter(1)
    public int b;
    @Parameterized.Parameter(2)
    public int result;
//    public int a;
//    public int b;
//    public int result;
//    // 可以使用构造方法代替
//    public ParameterizedTestFields(int a, int b, int result) {
//        super();
//        this.a = a;
//        this.b = b;
//        this.result = result;
//    }
    // creates the test data
    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][] { { 1 , 2, 2 }, { 5, 3, 15 }, { 121, 4, 484 } };
        return Arrays.asList(data);
    }
    @Test
    public void testMultiplyException() {
        Usually_Test test = new Usually_Test();
        Assert.assertEquals("Result", result, test.mul(a, b));
    }
}

   参数不匹配将会抛出java.lang.IllegalArgumentException: wrong number of arguments

6:分类测试(Category)

  •  @Category 可以作用于类上,方法上
  •  聚合测试属性
  •  @Categories.ExcludeCategory 要排除测试的那些类
  •  @Categories.IncludeCategory  要测试包含测试的那些类
// 两个标记接口
interface FastTests { }
interface SlowTests { }
// 主测试类
@RunWith(Categories.class)
@Categories.IncludeCategory({FastTests.class})
@SuiteClasses({A.class,B.class})
public class TestAndCategory {
    /**
     * A: 这里A类的 test_m1 被FastTests标注  test_m2 被SlowTests接口标注
     * B: 这里B类被 SlowTests FastTests两个接口标准
     */ 
    @Test
    public void  test() {
    }
}
// 两个测试类
public class A{
    @Test
    @Category(FastTests.class)
    public void test_m1() {
        System.out.println("A类的 test_m1 FastTests 被执行");
    }
    @Test
    @Category(SlowTests.class)
    public void test_m2() {
        System.out.println("A类的 test_m2 SlowTests 被执行");
    }
}
@Category({FastTests.class,SlowTests.class}) // 类中的方法都会被标注
public class B{
    @Test
    public void test_m() {
        Assert.assertTrue(System.getProperty("os.name").contains("Windows"));
    }
    
    @Test
    public void test_m2() {
        System.out.println("B类的 test_m2 SlowTests");
    }
}

7:Rule测试

 Junit中的规则 即实现了TestRule接口,已久为我们实现了以下一些内容

 

 规定 实现了TestRule接口的类构建实例必须用以下注解标准

  •  @Rule     @Rule是方法级别的,每个测试方法执行时都会调用被注解的Rule
  •  @RuleClass   在执行一个测试类的时候只会调用一次被注解的Rule
  •   要求 @Rule  @RuleClass 必须是Public的字段

ExpectedException 抛出异常例子

public class User_RuleTest {
    @Rule
    public ExpectedException exception=ExpectedException.none();
    /**
     * 1:必须抛出ArrayIndexOutOfBoundsException
     * 2:异常消息为1
     */
    @Test
    public void test_ExpectedException() {
        exception.expect(ArrayIndexOutOfBoundsException.class);
        exception.expectMessage("1");
        ThrowExceptionClass t = new ThrowExceptionClass();
        t.methodToBeTest(1);
    }
}
class ThrowExceptionClass{

    public void methodToBeTest(int i) {
        if (i == 1) {
            throw new ArrayIndexOutOfBoundsException("1");
        }
    }
}

    TemporaryFolder 创建零时文件例子(自动删除)

public class Use_Rule_Test2 {
    @Rule
    public TemporaryFolder tFolder=new TemporaryFolder();
    
    @Test
    public void tets_CreateTempFiles() throws IOException {
         File createdFolder = tFolder.newFolder("newfolder");
         File createdFile = tFolder.newFile("myfilefile.txt");
         Assert.assertTrue(createdFile.exists());
         Assert.assertTrue(createdFolder.exists());
    }

}

 8: 常见异常

java.lang.Exception: No tests found matching:  导入hamcrest-all 1.3版本 我是junit 4.12

java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=test_ExpectedException], {ExactMatcher:fDisplayName=test_ExpectedException(Junit_case.User_RuleTest)], {LeadingIdentifierMatcher:fClassName=Junit_case.User_RuleTest,fLeadingIdentifier=test_ExpectedException]] from org.junit.internal.requests.ClassRequest@60215eee
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:40)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createFilteredTest(JUnit4TestLoader.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:74)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:525)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

org.junit.internal.runners.rules.ValidationError: The @Rule 'exception' must be public. 字段要求为Public
at org.junit.internal.runners.rules.RuleMemberValidator$MemberMustBePublic.validate(RuleMemberValidator.java:222)
at org.junit.internal.runners.rules.RuleMemberValidator.validateMember(RuleMemberValidator.java:99)
at org.junit.internal.runners.rules.RuleMemberValidator.validate(RuleMemberValidator.java:93)
at org.junit.runners.BlockJUnit4ClassRunner.validateFields(BlockJUnit4ClassRunner.java:196)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:129)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:90)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:525)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

猜你喜欢

转载自www.cnblogs.com/dgwblog/p/11768886.html
今日推荐