单元测试

来源:互联网 发布:网页抢购软件 编辑:程序博客网 时间:2024/05/17 01:46
单元测试小记:
1.RunWith,指定执行类(运行器)。
例子:
@RunWith(Parameterized.class)
@Parameters
//参数化运行器
@RunWith(SpringJUnit4ClassRunner.class);
@ContextConfiguration(locations = {"classpath:applicationContext.xml"}
//Spring
@RunWith(SpringJUnit4ClassRunner.class);
@SpringBootTest(classes = ProviderApplicationMain.class);
//Springboot
@RunWith(JUnit4.class);
//JUint自带,默认运行器
@RunWith(Suite.class)
@SuiteClasses({ATest.class,BTest.class,CTest.class});
//将ABC类一起执行


2.@Test
@Test(expected = ArithmeticException.class)

       某函数{

        System.out.println(999);

        System.out.println(9/0);

        System.out.println(888);

}

以上代码虽然不报错,但是不会输出888。expected参数也不能用在@Before上,不会正确运行。



3.@Before方法执行前运行//是每个方法前都执行此方法,包括带有Before的方法自身。每一组方法(Before+Test+After)会使用同一些外部属性。比如
class A{
doule a = Math.random();
@Before
@Test
public void aaaaaa(){
输出-random;
}
}

以上两次random是相同的。



4.@After方法执行后运行
5.@BeforeClass类执行前运行

6.@AfterClass类执行后运行

所以一个Junit 4 的单元测试用例执行顺序为:@BeforeClass –> @Before –> @Test –> @After –> @AfterClass;每一个测试方法的调用顺序为:@Before –> @Test –> @After。


7.捕捉错误除了2方法还可以用try-catch

原创粉丝点击