我将如何为以半径为参数的圆形类编写构造函数测试代码
这是生产代码:
using MyGeometry.Abstract;
using MyGeometry.Interface;
namespace MyGeometry.RealShapes
{
public class Circle : Shape, IFlatShape
{
public Circle(int radius)
{
Length = radius;
}
public double CalculateArea()
{
return 3.14*Length*Length;
}
public double CalculatePerimeter()
{
return 2*3.14*Length;
}
}
}
这是测试用例:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyGeometry.RealShapes;
namespace ShapeTest
{
[TestClass]
public class CircleTest
{
[TestMethod]
public void CircleConstructorTest()
{
//what should be written here???
}
}
}
这取决于您要测试的内容。 如果你试图测试你的构造函数在你给它错误的输入时抛出异常,你可以写一些类似于:
[TestMethod]
public void ShouldThrowExceptionIfArgumentIsOutOfRange()
{
try
{
new Circle(-1);
Assert.Fail("Constructor did not throw exception");
}
catch (ArgumentOutOfRangeException)
{
Assert.Pass();
}
}
尽管这仅在您希望仅在构造函数中测试行为时才有用。 如果要测试与类方法相关的代码,则可以编写方法来测试这些代码,提供输入并检查方法的结果。
正如@Matthew所说,您可以测试半径参数是否大于 0
namespace ShapeTest
{
[TestClass]
public class CircleTest
{
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void RadiusIsGreaterThanZero()
{
Circle c = new Circle(0);
}
}
}
现在,如果您希望构造函数通过此测试,则应将 Circle 类修改为:
using MyGeometry.Abstract;
using MyGeometry.Interface;
namespace MyGeometry.RealShapes
{
public class Circle : Shape, IFlatShape
{
public Circle(int radius)
{
if(radius > 0)
Length = radius;
else
throw new ArgumentOutOfRangeException("Radius must be greater than zero");
}
......
}
}