如何为radius类编写构造函数测试代码,并将radius作为参数
这是生产代码:
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???
}
}
}
答案 0 :(得分:1)
这取决于您要测试的内容。如果你试图测试你的构造函数如果给它输入错误就抛出异常,你可以写一些类似的东西:
[TestMethod]
public void ShouldThrowExceptionIfArgumentIsOutOfRange()
{
try
{
new Circle(-1);
Assert.Fail("Constructor did not throw exception");
}
catch (ArgumentOutOfRangeException)
{
Assert.Pass();
}
}
虽然这只是在你想要单独在构造函数中测试行为时才有用。如果要测试与类方法相关的代码,可以编写测试方法,提供输入并检查方法的结果。
答案 1 :(得分:0)
正如@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");
}
......
}
}