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

在上一篇文章中写了关于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的用例过程,其实还是很轻松愉快的。

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值