我是单位测试世界的新手,所以请饶我。问题的目标是测试如下所述的课程:
public class Engine
{
#region Members
private EnumDefinition.EngineRunningState runningState;
private ComponentController componentController;
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
#endregion
#region Constructor
public Engine(ComponentController componentController)
{
this.componentController = componentController;
}
#endregion
#region Properties
public EnumDefinition.EngineRunningState RunningState
{
get
{
return runningState;
}
private set
{
if (value != runningState)
{
componentController.EngineRunningStateChangedEvent += OnEngineRunningStateChange;
}
}
}
#endregion
/// <summary>
/// Start the Engine Request
/// </summary>
public void StartEngineRequest()
{
// Check Engine Status
if (runningState == EnumDefinition.EngineRunningState.Off)
{
componentController.SetEngineRequestToActive();
}
else if (runningState == EnumDefinition.EngineRunningState.Error)
{
logger.Trace("Engine Start Request Sent on a ENGINE ERROR!!!!!!");
}
else
{
logger.Trace("Engine Start Request, Engine is still ON");
}
}
private void OnEngineRunningStateChange(object sender, EngineRunningStateArgs e)
{
runningState = e.runningStateofEngine;
}
}
我想测试Engine中的公共函数。现在我介绍我的Test课程:
[TestFixture]
public class EngineTest
{
[Test]
public void StartEngineRequestTest()
{
Mock<ComponentController> mockComponentController = new Mock<ComponentController>();
Mock<EngineRunningStateArgs> mockEngineRunningStateArgs =
new Mock<EngineRunningStateArgs>(EnumDefinition.EngineRunningState.On);
var engineTest = new Engine(mockComponentController.Object);
mockComponentController.Raise(mock => mock.EngineRunningStateChangedEvent += null, mockEngineRunningStateArgs.Object);
engineTest.StartEngineRequest();
}
}
mt test失败,如下所述:
Result StackTrace:
at Moq.Extensions.GetEvent[TMock](Action 1 eventExpression, TMock mock)
at Moq.Mock 1.Raise(Action 1 eventExpression, EventArgs args)
at AutoTugTest.EngineTest.StartEngineRequestTest() in C:\GatewayController\01 Working Copy\GatewayComputer\AutoTugTest\EngineTest.cs:line 23
Result Message: System.ArgumentException : Expression is not an event attach or detach, or the event is declared in a class but not marked virtual.
我不知道发生了什么。
我只想从ComponentController
抛出事件名称为EngineRunningStateChangedEvent
的事件参数。
请建议。
答案 0 :(得分:2)
Moq只能模拟虚拟成员。它擅长模拟接口,因为没有实现,但如果你想模拟一个具体的类,你模拟的成员将需要是虚拟的。这让Moq包裹了真实的&#39;用它实现的。