美文网首页
单元测试之JUnit

单元测试之JUnit

作者: sylcrq | 来源:发表于2016-11-16 13:52 被阅读390次

Unit Testing with JUnit - Tutorial

2. 测试术语

  • Code (or application) under test:指被测试的代码
  • Test fixture:??
  • Unit tests and unit testing:单元测试的目标是一小段代码,例如一个方法或一个类。
  • Integration tests
  • Performance tests
  • Behavior vs. state testingbehavior testing检查特定方法是否被调用with正确的参数;State testing验证函数调用的结果(返回值)

3. 测试管理

通常单元测试代码放在特定的目录下,与项目源代码分开

4. 使用JUnit

一个JUnit测试就是测试类中的一个方法,编写一个JUnit 4测试只要在函数上标注@org.junit.Test注解。这个函数就会执行测试代码。可以使用assert语句检查实际的返回值是否和期望的一致。

一个简单的JUnit测试例子:

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class MyTests {
    @Test
    public void multiplicationOfZeroIntegersShouldReturnZero() {
        MyClass tester = new MyClass(); // MyClass is tested
        // assert statements
        assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0));
        assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10));
        assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0));
    }
}

JUnit测试的命名规范,以被测试类的名称添加后缀"-test"来命名测试类

JUnit test suites:如果有多个测试类,可以把它们结合到一个test suite

5. JUnit代码结构

  • JUnit 4通过注解标示一个函数为测试方法,并且对它们进行配置
Annotation Description
@Test public void method() The @Test annotation identifies a method as a test method.
@Test (expected = Exception.class) 如果函数没有抛出该异常,测试失败
@Test(timeout=100) 如果函数执行时间大于100ms,测试失败
@Before public void method() 在每个测试开始之前都会执行,用于初始化测试环境
@After public void method() 在每个测试结束后都会执行
@BeforeClass public static void method() 在所有测试开始之前只执行一次
@AfterClass public static void method() 在所有测试执行结束之后只执行一次
@Ignore or @Ignore("Why disabled") 忽略该测试函数
  • Assert语句
Statement Description
fail(message) 直接使测试失败
assertTrue([message,] boolean condition) 检查boolean condition是否为true
assertFalse([message,] boolean condition) 检查boolean condition是否为false
assertEquals([message,] expected, actual) 测试两个值是否相同
assertEquals([message,] expected, actual, tolerance) 测试float或double值是否相同
assertNull([message,] object) 检查对象为空
assertNotNull([message,] object) 检查对象不为空
assertSame([message,] expected, actual) 检查两个变量引用同一个对象
assertNotSame([message,] expected, actual) 检查两个变量引用不同的对象

JUnit假设所有测试函数可以任意的顺序执行,所以在写测试代码时不应该依赖其他测试的执行顺序

在执行时动态忽略一个测试:

Assume.assumeFalse(System.getProperty("os.name").contains("Linux"));

10.JUnit高级

  • Parameterized test
  • JUnit Rules
    通过JUnit Rules可以为测试类中的每个测试添加行为。可以为类型为TestRule的属性标示@Rule注解。创建的对象可以在测试函数中使用和配置。
public class RuleTester {
    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void testUsingTempFolder() throws IOException {
        File createdFolder = folder.newFolder("newfolder");
        File createdFile = folder.newFile("myfilefile.txt");
        assertTrue(createdFile.exists());
    }
}
  • Writing custom JUnit rules
  • Categories

相关文章

网友评论

      本文标题:单元测试之JUnit

      本文链接:https://www.haomeiwen.com/subject/dycrpttx.html