我的問題很簡單(與更有經驗的開發者可能也知道):單元測試UI方法
我如何單元測試這個方法(我知道,沒有一種方法,因爲它不是在一個班,但讓假設它是)?
void drawRegularPolygon(int numberOfPoint, Point centerPoint, double radius)
{
double angleDelta = 2 * PI/numberOfPoint;
Point firstPoint = new Point(centerPoint.x + radius, centerPoint.y);
for (int i = 1; i < numberOfPoint; i++) {
double angle = angleDelta * i;
Point secondPoint = new Point(centerPoint.x + radius * cos(angle), centerPoint.y + radius * sin(angle));
DrawLine(firstPoint, secondPoint);
firstPoint = secondPoint;
}
}
我接受的回答說:「你應該重構這個樣子this
甚至考慮測試之前」。
編輯1: 我剛剛在我的代碼中發現了一個錯誤,但我留在那裏有一個單元測試應該如何捕捉它的想法。
編輯2: 我也想過另一種解決方案
Array<Line> regularPolygonLines(int numberOfPoint, Point centerPoint, double radius)
{
Array<Line> lines = new Array<Line>;
double angleDelta = 2 * PI/numberOfPoint;
Point firstPoint = new Point(centerPoint.x + radius, centerPoint.y);
for (int i = 1; i <= numberOfPoint; i++) {
double angle = angleDelta * i;
Point secondPoint = new Point(centerPoint.x + radius * cos(angle), centerPoint.y + radius * sin(angle));
lines.add(new Line(firstPoint, secondPoint));
firstPoint = secondPoint;
}
return lines;
}
void drawRegularPolygon(int numberOfPoint, Point centerPoint, double radius)
{
Array<Line> lines = regularPolygonLines(numberOfPoint, centerPoint, radius);
for (Line line in lines) {
DrawLine(line.firstPoint, line.secondPoint);
}
}
,並在這其中,regularPolygonLines
方法可以檢測,但drawRegularPolygon
不能。
你在正確的軌道上你拉出*計算*並隔離*渲染*。事實上,計算可以被測試,您可以將其視爲用戶界面的「業務規則」。它也有助於SRP和清晰度。 – toddmo 2015-03-10 17:20:12