测试驱动开发(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的用例过程,其实还是很轻松愉快的。
还没有评论,来说两句吧...