关闭

使用JUnit进行单元测试

发表于:2017-3-14 11:03

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:HollisChuang\\\'s Bl    来源:51Testing软件测试网采编

  异常测试
  你可以测试代码是否它抛出了想要得到的异常。expected 参数和 @Test 注释一起使用。现在让我们看看活动中的 @Test(expected)。
  @Test(expected = NullPointerException.class)
  public void testException() {
  throw new NullPointerException();
  }
  所有测试代码
  代码地址
package com.hollischuang.effective.unitest.service;
import org.junit.*;
/**
* @author Hollis 17/1/7.
*/
public class JUnitTest {
/**
* 只执行一次,在整个类执行之前执行
*/
@BeforeClass
public static void beforeClass() {
System.out.println("in before class");
}
/**
* 只执行一次,在整个类执行之后执行
*/
@AfterClass
public static void afterClass() {
System.out.println("in after class");
}
/**
* 每个测试方法被执行前都被执行一次
*/
@Before
public void before() {
System.out.println("in before");
}
/**
* 每个测试方法被执行后都被执行一次
*/
@After
public void after() {
System.out.println("in after");
}
// test case 1
@Test
public void testCase1() {
System.out.println("in test case 1");
}
// test case 2
@Test
public void testCase2() {
System.out.println("in test case 2");
}
/**
* 测试assertEquals
*/
@Test
public void testEquals() {
Assert.assertEquals(1 + 2, 3);
}
/**
* 测试assertTrue
*/
@Test
public void testTrue() {
Assert.assertTrue(1 + 2 == 3);
}
/**
* 测试assertFalse
*/
@Test
public void testFals() {
Assert.assertFalse(1 + 2 == 4);
}
/**
* 测试assertNotNull
*/
@Test
public void assertNotNull() {
Assert.assertNotNull("not null");
}
/**
* 测试assertNull
*/
@Test
public void assertNull() {
Assert.assertNull(null);
}
/**
* 测试fail和Ignore
*/
@Test
@Ignore
public void assertFail() {
Assert.fail();
}
/**
* 测试异常
*/
@Test(expected = NullPointerException.class)
public void testException() {
throw new NullPointerException();
}
/**
* 测试时间
*/
@Test(timeout = 1000)
public void testTimeoutSuccess() {
// do nothing
}
/**
* 测试时间
*/
@Test(timeout = 1000)
public void testTimeoutFailed() {
while (true) {
}
}
}
  总结
  本文主要介绍了JUnit的常见用法,后面会专门写一篇文章介绍如何将JUnit和Spring集合到一起。
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号