测试驱动开发(TDD)实战体验

Dear 丶 2023-10-10 09:36 100阅读 0赞

在上一篇文章中写了关于TDD的理论,感兴趣的小伙伴可以去阅读一下。今天这篇文章以一个简单的例子来体验一下TDD的过程。

环境
  • Java 8
  • Junit 5
需求

我们有这样子的一个需求:客户需要一个长方形,能够给长方形设置宽和高,并且能够计算面积

1.编写测试用例
  • 此时的Rectangle类如下

    class Rectangle {

    1. private double width;
    2. private double height;
    3. public void setWidth(double width) {
    4. this.width = width;
    5. }
    6. public void setHeight(double height) {
    7. this.height = height;
    8. }

    }

  • 编写测试case

    public class RectangleTest {

    1. @Test
    2. void should_return_20_when_width_2_and_height_10() {
    3. double width = 2;
    4. double height = 10;
    5. Rectangle rectangle = new Rectangle();
    6. rectangle.setWidth(width);
    7. rectangle.setHeight(height);
    8. assert (rectangle.count(width, height) == 20);
    9. }

    }

2.运行测试用例

就会看到测试case运行失败了(因为你还没写功能代码)

3.编写业务代码
  1. class Rectangle {
  2. private double width;
  3. private double height;
  4. public void setWidth(double width) {
  5. this.width = width;
  6. }
  7. public void setHeight(double height) {
  8. this.height = height;
  9. }
  10. public double count(double width, double height) {
  11. return width * height;
  12. }
  13. }
4.运行测试用例,然后看到测试用例通过了
5.对代码查缺补漏,进行重构
  • 补充测试用例

    public class RectangleTest {

    1. @Test
    2. void should_return_20_when_width_2_and_height_10() {
    3. double width = 2;
    4. double height = 10;
    5. Rectangle rectangle = new Rectangle();
    6. rectangle.setWidth(width);
    7. rectangle.setHeight(height);
    8. assert (rectangle.count(width, height) == 20);
    9. }
    10. @Test
    11. void should_throw_exception_when_width_given_error_value() {
    12. double width = -10;
    13. double height = 10;
    14. Rectangle rectangle = new Rectangle();
    15. assertThrows(IllegalArgumentException.class, () -> rectangle.count(width, height));
    16. }

    }

  • 运行测试用例,发现失败了

  • 然后补充代码,此时的Rectangle类如下

    class Rectangle {

    1. private double width;
    2. private double height;
    3. public void setWidth(double width) {
    4. this.width = width;
    5. }
    6. public void setHeight(double height) {
    7. this.height = height;
    8. }
    9. public double count(double width, double height) {
    10. if (width <= 0 || height <= 0) {
    11. throw new IllegalArgumentException();
    12. }
    13. return width * height;
    14. }

    }

以上就是一个简单的TDD的用例过程,其实还是很轻松愉快的。

发表评论

表情:
评论列表 (有 0 条评论,100人围观)

还没有评论,来说两句吧...

相关阅读

    相关 测试驱动开发(TDD)的理论基础

    开始理论介绍之前,先思考一个问题:**软件开发中最重要的是什么?** * 可能有的小伙伴就会说:良好的数据库设计,一个健壮可扩展的架构,规范的编码风格,设计文档等。...

    相关 TDD测试驱动开发

    TDD(Test-Driven Development)是敏捷开发中的一项核心实践和技术,也是一种设计方法论,其基本思想是:在明确要开发某个功能后,在开发功能代码之前,

    相关 TDD (test driver development)测试驱动开发

    \\为什么需要测试驱动/或者说需要单元测试 我们工作接触的软件项目,不是学生时代,玩一玩就不管了,工作的项目,需要长期维护,并且随着时间的推移需要增加新的需求,进行修改,优化