我正在尝试对此类 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(); }
}
如果这个类是测试或库项目的一部分,那就没问题了。但是当它在服务项目中时,起订量给我这个错误:
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);
}
我愿意继续,所以这门课将加入图书馆课,但如果有人能向我解释这种行为,我会非常高兴......
谢谢,
最佳答案
您的 Setup
方法需要有一个 Returns
,因为您正在模拟的那些方法都返回一个 bool。
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());
}
关于c# - 当类在服务项目中时,最小起订量在不可覆盖的成员上抛出无效设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6469283/