我有一个支持多种部署模式的项目: InMem,OnPremise,Cloud 。 此外,每个项目都有像TimeDistance这样的小型服务,可以连接到WCF,也可以连接到API。
在unitTestMockup中,我可以说我想使用哪一个:
Service.TimeDistance = new WCFTimeDistance() / new APITimeDistance().
到目前为止,我只有 WCFTimeDistance ,但现在我们处于转换模式以转移到APITimeDistance但同时我想要运行测试运行两次,一次使用带有API的WCF一次。< / p>
这样做的好方法是什么?
I use C# 4.5
Microsoft.VisualStudio.QualityTools.UnitTestFramework as framework for unitTests
所需工作流程的一个简单示例是:
1)Mockup: Service.TimeDistance = new WCFTimeDistance();
2)UnitTest: CheckDistanceBetweenTwoLocationsTest()
{
Service.TimeDistance.CalculateDistance(Location1, Location2) // WCFTimeDistance
}
3)Mockup: Service.TimeDistance = new APITimeDistance();
UnitTest: CheckDistanceBetweenTwoLocationsTest()
{
4)Service.TimeDistance.CalculateDistance(Location1, Location2) // APITimeDistance
}
答案 0 :(得分:3)
创建两个单元测试。另请参阅使用抽象而不是静态类。它会使模拟和测试变得更容易。
这适用于您当前的设置
[TestClass]
public class TimeDistanceTests {
//change these to the needed types
object Location1;
object Location2;
double expected;
[TestInitialize]
public void Init() {
//...setup the two locations and expectations
Location1 = //...
Location2 = //...
expected = //...the distance.
}
[TestMethod]
public void Check_Distance_Between_Two_Locations_Using_WCF() {
//Arrange
var sut = new WCFTimeDistance();
//Act
var actual = sut.CalculateDistance(Location1, Location2);
//Assert
//...some assertion proving that test passes or failed
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Check_Distance_Between_Two_Locations_Using_API() {
//Arrange
var sut = new APITimeDistance();
//Act
var actual = sut.CalculateDistance(Location1, Location2);
//Assert
//...some assertion proving that test passes or failed
Assert.AreEqual(expected, actual);
}
}
理想情况下,您需要抽象服务。假设像
这样的东西public interface ITimeDistance {
double CalculateDistance(Location location1, Location location2);
}
您的服务将使用抽象而非结果。
public class Service {
ITimeDistance timeDistance
public Service(ITimeDistance timeDistance) {
this.timeDistance = timeDistance;
}
public ITimeDistance TimeDistance { get { return timeDistance; } }
}
现在,在您的单元测试中,您可以交换时间距离服务的不同实现。