单元测试

单元测试

1.单元测试的必要性

  1. 千里之堤,毁于蚁穴。
  2. 每个最基本的单位运算结果正确,最终系统所提供的服务才有保障。

2.如何进行单元测试

  1. 可以使用junit。
  2. 单元测试放在什么地方?对于一个Maven项目,源码放在main中;单元测试放在test下,和源码路径保持一致。
  3. 单元测试类如何起名?要测试的类后加Test,如UserController,单元测试类为UserControllerTest。
  4. 单元测试的方法如何起名?通过下划线区分,别说明要测试的功能。
@GetMapping("/get/{id}")
public User getUserById(@PathVariable("id") int id) throws RuntimeException {
    if (id <= 0) {
        throw new RuntimeException("id不能小于等于0");
    }

    User user = find(id);

    try {
        Optional.ofNullable(user).orElseThrow(() -> new RuntimeException("id错误"));
    }catch (RuntimeException e) {
        throw new RuntimeException("id错误");
    }
    return user;
}

@Test
public void getUserById_should_throw_exception() {
    User user = userController.getUserById(0);
}

@Test
public void getUserById_should_username_tom() {
    User user = userController.getUserById(1);

    Assert.isTrue(!"tom".equals(user.getName()), "username should is tom");
}

3.需要注意的地方

  1. 每一个单元测试的方法,只是要测试单元的一种情况。单元测试的方法中不能有if...else...。
  2. 如果一个方法没有办法进行单元测试,就说明这个方法需要重构了。
  3. 敏捷开发中提倡少写开发文档,好的单元测试就是一个文档库。
posted @ 2021-09-21 21:27  行稳致远方  阅读(15)  评论(0)    收藏  举报