嗨,我是 Moq 框架的新手,对如何使用它有一些疑问。我会举个例子,希望得到答案。
我有两个类,一个接口和一个实现:
public class Vehicle{
public string RegistrationNumber {get; set;}
public long VehicleIdentifier { get; set; }
public Tyre TyreSpecification { get; set; }
}
public class Tyre {
public long NumberOfTyres {get; set;}
public long TyreSize { get; set;}
}
public interface ISelecter {
Vehicle GetVehicleByRegistrationNumber(string registrationNumber);
Tyre GetTyreSpecification(long vehicleIdentifier);
}
public class Selecter : ISelecter
{
public Vehicle GetVehicleByRegistrationNumber(string registrationNumber)
{
var vehicle = 'Database will give us the vehicle specification';
//Then we do things with the vehicle object
//Get the tyre specification
vehicle.TyreSpecification = GetTyreSpecification(vehicle.VehicleIdentifier);
return vehicle;
}
public Tyre GetTyreSpecification(long vehicleIdentifier)
{
var tyre = 'external manufacture system gets the tyre specification';
//Then do thing with the tyre before returning the object
return tyre;
}
}
我想为这些方法编写两个测试。问题是当我编写测试时,GetVehicleByRegistrationNumber
我不知道如何模拟对GetTyreSpecification
.
测试方法如下所示:
[TestClass]
public class SelecterTest
{
[TestMethod]
public void GetTyreSpecification_test()
{
//Arrange
var tyre = new Tyre { NumberOfTyres = 4, TyreSize = 18 };
var mockSelecter = new Mock<ISelecter>();
mockSelecter.SetUp(s=>s.GetTyreSpecification(It.IsAny<long>())).Returns(tyre);
//Act
var tyreSpec = mockSelecter.Object.GetTyreSpecification(123456);
//Assert
Assert.IsTrue(tyreSpec.NumberOfTyres == 4 && tyreSpec.TyreSize == 18);
}
[TestMethod]
public void GetVehicleByRegistrationNumber_test()
{
//Arrange
var vehicle= new Vehicle { VehicleIdentifier = 123456, RegistrationNumber = ABC123, TyreSpecification = new Tyre { Tyresize = 18, NumberOfTyres = 4 }};
var mockSelecter = new Mock<ISelecter>();
mockSelecter.SetUp(s=>s.GetVehicleByRegistrationNumber(It.IsAny<string> ())).Returns(vehicle);
//Act
var vehicle = mockSelecter.Object.GetVehicleByregistrationNumber(123456);
//Assert
Assert.IsTrue(vehicle.Registrationnumber == "ABC123";
}
}
在测试方法GetVehicleByRegistrationNumber_test
中我如何模拟调用getTyreSpecification
?