junit4.1.2

test

Posted by Static on October 13, 2019

junit版本:4.1.2 参考

常用注解:

  1. @BeforeClass:所有test方法执行之前执行
  2. @AfterClass:在所有test方法执行完之后执行,比如:连接关闭,资源回收等操作
  3. @Before:在每个case执行之前都会run
  4. @After:在每个case执行完之后都会run
  5. @Ignore:整个测试类run时忽略当前case
  6. @Test:当前方法将会被当做测试用例,timeout():方法运行时间限制,expected():期待抛出的异常
  7. @RunWith:用于测试类,用来确定这个类怎么运行的。默认BlockJUnit4ClassRunner运行器

@RunWith

1. Parameterized.class
/*
参数化运行器,配合@Parameters 使用
@see share ParametersDemo.java
*/
@RunWith(Parameterized.class)
@AllArgsConstructor
public class ParametersDemo {
    private int numberOne;
    private int numberTwo;
    private int expectedNumber;

    /**
     * 1)必须由@Parameters注解修饰
     * 2)必须为public static的
     * 3)必须返回Collection类型
     * 4)方法名字不做要求
     * 5)无参数
     */
    @Parameters
    public static Collection mockData() {
        return Arrays.asList(new Integer[][]{
                {-1, -2, -1},
                {0, 2, 2},
                {-1, 1, 1},
                {1, 2, 2}});
    }

    @Test
    public void test() {
        int max = Integer.max(numberOne, numberTwo);
        Assert.assertEquals(expectedNumber, max);
    }

}
2. Suite.class
/*
测试集运行器配合使用测试集功能
一次性测试A、B、C类中的测试方法
*/
@RunWith(Suite.class)
@SuiteClasses({A.class,B.class,C.class})
public class Demo{}
3. Categories.class
@RunWith(Categories.class)
/**
 * 执行哪些类型
 */
@Categories.IncludeCategory({Character.class, Animal.class})
/**
 * 哪些类型的测试
 */
@Suite.SuiteClasses({A.class, B.class, Dog.class})
public class CategoriesDemo {}

public interface Animal {}

public interface Character {}

@Category(Character.class)
public class A {
    @Test
    public void print() {
        System.out.println("A");
    }
}

public class B {
    @Test
    public void print() {
        System.out.println("B");
    }
}

public class Dog {
    @Test
    @Category(Animal.class)
    public void print() {
        System.out.println("Dog");
    }
}
4. SpringJUnit4ClassRunner.class
/**
 * spring测试使用
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-test.xml"})
public class SpringTestDemo{}

@Rule

规则器,提供了测试用例在执行过程中通用功能的共享的能力

1. TemporaryFolder

创建零时测试文件,并在测试后自动删除

public class TemporaryFolderDemo {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void temporaryFolder() throws IOException {
        File createdFolder = folder.newFolder("rule");
        File createdFile = folder.newFile("test.txt");

        assertTrue(createdFile.exists());
        assertTrue(createdFolder.exists());

    }
}
2. ErrorCollector

在一个测试方法中收集多个错误,抛出异常时,程序不会停止运行,直到最后,会将所有搜集的异常抛出

public class ErrorCollectorDemo {
    @Rule
    public ErrorCollector errorCollector = new ErrorCollector();

    @Test
    public void errorCollector() {
        try {
           throw new RuntimeException();
        } catch (Throwable e) {
            errorCollector.addError(e);
        }

        Integer out = errorCollector.checkSucceeds(() -> {
            //异常 结果不能返回。无异常 返回结果
            Assert.assertTrue(true);
            return 1;
        });
    }
}
3. Verifier

校验对象状态,在 @After 步骤之后执行

public class VerifierDemo {
    private List<String> list = Lists.newArrayList();

    @Rule
    public TestName testName = new TestName();

    @Rule
    public Verifier verifier = new Verifier() {
        /**
         * 每个case执行之后进行校验
         */
        @Override
        public void verify() {
            //不为空校验
            if (Objects.isNull(list) || list.size() == 0) {
                throw new RuntimeException("list size is null");
            }
        }
    };

    @Test
    public void testOne() {
        System.out.println(testName.getMethodName());
    }

    @Test
    public void testTwo() {
        list.add("test");
    }

    /**
     * verifier 运行在 @After 步骤之后
     */
    @After
    public void afterExecute() {
        System.out.println(testName.getMethodName() + " after");
    }
}
4. TestWatcher

在方法执行期间添加执行日志

public class TestWatcherDemo {
    private static String watchedLog = "";

    @Rule
    public TestWatcher watchman = new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description description) {
            watchedLog += description + "\n";
            System.out.println(watchedLog);
        }

        @Override
        protected void succeeded(Description description) {
            watchedLog += description + "\n";
            System.out.println(watchedLog);
        }
    };

    @Test
    public void fails() {
        fail();
    }

    @Test
    public void succeeds() {
    }
}
5. TestName

保留测试的方法名

public class TestNameDemo {
    @Rule
    public TestName testName = new TestName();

    @Test
    public void testA() {
        Assert.assertEquals("testA", testName.getMethodName());
    }

    @Test
    public void testB() {
        Assert.assertEquals("testB", testName.getMethodName());
    }
}
6. Timeout

限制测试方法执行时间

public class TimeoutDemo {
    @Rule
    public Timeout timeout = Timeout.seconds(1);

    @Test
    public void test() throws InterruptedException {
        Thread.sleep(1);
    }

}
7. ExpectedException

校验抛出的异常

public class ExpectedExceptionDemo {
    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void throwsIllegalArgumentExceptionIfIconIsNull() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Negative value not allowed");
        throw new IllegalArgumentException("Negative value not allowed");
    }
}