我正在尝试对这个类ServizioController进行单元测试:
public class ServizioController : IServizioController
{
public virtual void PerformAction(Super.Core.Servizio servizio)
{
}
public virtual bool Start()
{ throw new NotImplementedException(); }
public virtual bool Stop()
{ throw new NotImplementedException(); }
public virtual bool Continue()
{ throw new NotImplementedException(); }
}
如果此类是测试或库项目的一部分,那就没问题了。但当它在服务项目中时,Moq正在向我抛出这个错误:
Invalid setup on a non-overridable member: x => x.Start()
我的测试看起来像这样:
[TestMethod]
public void ServizioController_PerformAction_Start()
{
//Arrange
bool _start, _stop, _continue;
_start = _stop = _continue = false;
Super.Core.Servizio s = new Super.Core.Servizio()
{
Action = ServizioAction.START.ToString()
};
var mock = new Mock<ServizioController>() { CallBase = true };;
mock.Setup(x => x.Start())
.Callback(() => _start = true);
mock.Setup(x => x.Stop())
.Callback(() => _stop = true);
mock.Setup(x => x.Continue())
.Callback(() => _continue = true);
//Act
mock.Object.PerformAction(s);
//Assert
Assert.IsTrue(_start);
Assert.IsFalse(_stop);
Assert.IsFalse(_continue);
}
我愿意继续,所以本课程将加入图书馆课程,但如果有人能解释我这种行为,我会非常高兴...
感谢,
答案 0 :(得分:0)
您的Setup
方法需要Returns
,因为您正在嘲笑的那些方法都会返回一个布尔值。
mock.Setup(x => x.Start()).Returns(true);
在旁注中,您不需要在此实例中使用Callback
,因为Verify
将为您完成工作
public void ServizioController_PerformAction_Start()
{
//Arrange
Super.Core.Servizio s = new Super.Core.Servizio()
{
Action = ServizioAction.START.ToString()
};
var mock = new Mock<ServizioController>() { CallBase = true };
mock.Setup(x => x.Start()).Returns(true);
mock.Setup(x => x.Stop()).Returns(true);
mock.Setup(x => x.Continue()).Returns(true);
//Act
mock.Object.PerformAction(s);
//Assert
mock.Verify(x => x.Start());
mock.Verify(x => x.Stop());
mock.Verify(x => x.Continue());
}