我们究竟何时需要使用Moq提供的.As
方法?
从快速入门文档:
// implementing multiple interfaces in mock
var foo = new Mock<IFoo>();
var disposableFoo = foo.As<IDisposable>();
// now the IFoo mock also implements IDisposable :)
disposableFoo.Setup(df => df.Dispose());
但我只是不明白我们为什么要那样做。你能给我一个实际的例子吗?
答案 0 :(得分:7)
当您需要测试实现多个接口的对象时,可以使用 As 方法。
在this示例中,如果输入对象也实现了IDisposable,则测试代码具有特定行为。像这样:
public void Execute(IFoo input)
{
// do process...
IDisposable disposable = input as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
课程实施:
public class ConcreteFoo: IFoo, IDisposable
{
...
}
编辑:
需要Moq的配置:
var foo = new Mock<IFoo>();
var disposableFoo = foo.As<IDisposable>();
disposableFoo.Setup(df => df.Dispose());
// Verify whether the Dispose() method was called
// That's true only if we use the As method from Moq.
testedClass.Execute(disposableFoo);
disposableFoo.Verify(m => m.Dispose());
答案 1 :(得分:5)
好的,这是一个例子。假设你有一个运输管理软件来管理汽车,飞行等的运动。有不同的车辆,但他们在陆地或空中移动(没有海来简化样品)。
public interface IMovingOnLand
{
string Move();
}
public interface IMovingInAir
{
string Move();
}
车辆/飞机有快速运输选择。
public interface IExpressTransport
{
string MoveDirectly();
}
有一个运输经理班负责移动所有车辆/飞机。它处理明确的运输方式与常规方式不同(为了简化起见,本例中它只根据是否是IExpressTransport打印不同的消息):
public class TransportManager
{
public string MoveItem(IMovingInAir airCraft)
{
if (airCraft is IExpressTransport)
{
return "Message from an express aircraft: " +
((IExpressTransport)airCraft).MoveDirectly();
}
return "Message from an aircraft: " + airCraft.Move();
}
public string MoveItem(IMovingOnLand landVehicle)
{
if (landVehicle is IExpressTransport)
{
return "Message from an express land vehicle: " +
landVehicle.Move() +
((IExpressTransport)landVehicle).MoveDirectly();
}
return "Message from a land vehicle: " + landVehicle.Move();
}
}
现在,您想测试飞机的行为是否与汽车不同。而且,如果常规航班的处理方式与快速航班不同。因此,您将对象测试为IMovingInAir
对象和IExpressTransport
。要仅测试航班行为,您只需将其创建为Mock<IMovingInAir>
即可。但要将航班扩展到快速航班,您必须使用As<IExpressTransport>()
方法:
[TestMethod]
public void TestTransportManager()
{
TransportManager manager = new TransportManager();
// Create a regular flight.
var flight = new Mock<IMovingInAir>();
flight.Setup(x => x.Move())
.Returns("Air craft moved to next stop.");
// Create a flight.
var flightExpress = new Mock<IMovingInAir>();
// Add standard behaviour.
flightExpress
.Setup(x => x.Move())
.Returns("Air craft moved to next stop.");
// Extend to express and add express flight behaviour.
flightExpress
.As<IExpressTransport>()
.Setup(x => x.MoveDirectly())
.Returns("Air craft moved directly to destination.");
// Get the results.
var res = manager.MoveItem(flight.Object);
var resExp = manager.MoveItem(flightExpress.Object);
// Sssert flight and express fligh returned different messages.
Assert.AreNotEqual(res, resExp);
// Assert the expected messages have been returned.
Assert.AreEqual("Message from an aircraft: Air craft moved to next stop.", res);
Assert.AreEqual("Message from an express aircraft: Air craft moved directly to destination.", resExp);
}