单元测试(2)helloworld

hello world

简介

编程入门的第一个例子,通常都是hello world。但是为了更完整地展示单元测试的优缺点,我们增加了额外的功能代码。

操作

首先,我们使用以下代码代替main方法。

public class JunitTest {

    @Test
    public void test() throws Exception {
        System.out.println("test() invoked");
    }
}

其次,我们在JunitTest中增加多个单元测试,同时在每个单元测试执行前后加上额外的逻辑。

public class JunitTest {

    @Before
    public void before() throws Exception {
        System.out.println("before() invoked");
    }

    @After
    public void after() throws Exception {
        System.out.println("after() invoked");
    }

    @Test
    public void test() throws Exception {
        System.out.println("test() invoked");
    }

    @Test
    public void test2() throws Exception {
        System.out.println("test2() invoked");
    }
}

在某些场景,我们可能需要每个单元测试访问相同的资源,比如测试类初始化、共享对象池等等。这时,我们可以使用@BeforeClass和@AfterClass来处理。这儿需要注意一点,注解的方法必须是public static void的,且放在所有方法的最前面

public class JunitTest {
    
    @BeforeClass
    public static void beforeClass() throws Exception {
        System.out.println("beforeClass() invoked");
    }

    @AfterClass
    public static void afterClass() throws Exception {
        System.out.println("afterClass() invoked");
    }

    @Before
    public void before() throws Exception {
        System.out.println("before() invoked");
    }

    @After
    public void after() throws Exception {
        System.out.println("after() invoked");
    }

    @Test
    public void test() throws Exception {
        System.out.println("test() invoked");
    }

    @Test
    public void test2() throws Exception {
        System.out.println("test2() invoked");
    }
}

在某些场景,我们可能会忽略某些单元测试,这时使用可以使用@Ignore,在4.x中,我们也可以使用“假设”来实现这种方式。

@Test
@Ignore("ignored function have not implemented")
public void testIgnored() {
    Assert.fail("ignored can't be invoked");
}
@Test
public void testOneEqualsOne() {
    assumeThat('1', is('1'));
    System.out.println("1 == 1");
}

@Test
public void testOneNotEqualsTwo() {
    assumeThat('1', is('2'));
    System.out.println("1 == 2");
}

优缺点

凡事有利有弊,重在权衡。

我认为的优点:

  • 代替main方法,在一个类中main只能有一个,而单元测试方法却可以有多个;
  • 提高开发人员对代码的认知度,集成测试框架引入@Test、@Before、@After、@BeforeClass、@AfterClass、Ignored等特性和机制,让我们更全面、更快地知道代码的不足,也从功能上完整地分析自己的代码优势、不足和bug。
  • 减轻QA的压力,单元测试能提早暴露问题,在开发阶段就发现问题并修复,而不用延迟到测试阶段,避免不必要的bug外放;
  • 方便引入XP和TDD。

我认为的缺点:

  • 增加了开发阶段额外的人力投入。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,969评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,422评论 25 708
  • 文章来自:http://blog.csdn.net/mj813/article/details/52451355 ...
    好大一只鹏阅读 9,215评论 2 126
  • 什么是单元测试 在计算机编程中,单元测试(Unit Testing)又称为模块测试, 是针对程序模块(软件设计的最...
    HelloCsl阅读 10,998评论 1 46
  • 吃过饭,我带一个女同事去领导那里喝茶,刚好哥哥也在,我们还没坐下呢,灯就熄了,中午睡觉公司会熄灯。这时,哥哥站起来...
    哈姆Y特公主阅读 200评论 0 0