如何使用不同的模型设置使 UnitTests 运行 两次

How to make UnitTests run twice with different mockup settings

我有一个支持多种部署模式的项目:InMem、OnPremise、Cloud。 此外,每个项目都有像 TimeDistance 这样的小服务,可以连接到 WCF,或者连接到 API。

在 unitTestMockup 中我可以说出我想使用哪一个:

Service.TimeDistance = new WCFTimeDistance() / new APITimeDistance().

直到现在我只有 WCFTimeDistance 但现在我们处于过渡模式以移动到 APITimeDistance 但与此同时我想要 运行 运行 的测试两次,一次使用 WCF 一次使用 API.

执行此操作的好方法是什么?

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
}

创建两个单元测试。还要考虑使用抽象而不是静态 类。这将使模拟和测试更容易。

这是针对您当前的设置

[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; } }
}

所以现在在你的单元测试中你可以交换你的时间距离服务的不同实现。