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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/wangchengming1/article/details/101293043

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

环境
  • Java 8
  • Junit 5
需求

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

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

    private double width;

    private double height;

    public void setWidth(double width) {
        this.width = width;
    }

    public void setHeight(double height) {
        this.height = height;
    }
}
  • 编写测试case
public class RectangleTest {

    @Test
    void should_return_20_when_width_2_and_height_10() {

        double width = 2;

        double height = 10;

        Rectangle rectangle = new Rectangle();

        rectangle.setWidth(width);
        rectangle.setHeight(height);

        assert (rectangle.count(width, height) == 20);
    }
}
2.运行测试用例

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

3.编写业务代码
class Rectangle {

    private double width;

    private double height;

    public void setWidth(double width) {
        this.width = width;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public double count(double width, double height) {
		 return width * height;
    }
}
4.运行测试用例,然后看到测试用例通过了
5.对代码查缺补漏,进行重构
  • 补充测试用例
public class RectangleTest {

    @Test
    void should_return_20_when_width_2_and_height_10() {

        double width = 2;

        double height = 10;

        Rectangle rectangle = new Rectangle();

        rectangle.setWidth(width);
        rectangle.setHeight(height);

        assert (rectangle.count(width, height) == 20);
    }

    @Test
    void should_throw_exception_when_width_given_error_value() {

        double width = -10;

        double height = 10;

        Rectangle rectangle = new Rectangle();

        assertThrows(IllegalArgumentException.class, () -> rectangle.count(width, height));
    }
}
  • 运行测试用例,发现失败了
  • 然后补充代码,此时的Rectangle类如下
class Rectangle {

    private double width;

    private double height;

    public void setWidth(double width) {
        this.width = width;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public double count(double width, double height) {
        if (width <= 0 || height <= 0) {
            throw new IllegalArgumentException();
        }
        return width * height;
    }
}

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

猜你喜欢

转载自blog.csdn.net/wangchengming1/article/details/101293043