【发布时间】:2015-04-06 15:44:52
【问题描述】:
我是单元测试的新手,如果我无法正确解释这个问题,请原谅我。我正在阅读一本书“单元测试的艺术第 2 版”并尝试在我的项目中实施单元测试。我目前在使用模拟(使用 NSubstitute 作为模拟框架)进行测试时遇到困难或困惑。
这是我的场景:
我有两个接口ICommand和IUser
public interface ICommand
{
string execute();
}
public interface IUserCalendar
{
string LoadCalendar();
}
我有一个类LoadCalendar,它实现了ICommand:
public class LoadCalendar : ICommand
{
private IUserCalendar user;
public string execute()
{
return this.user.LoadCalendar();
}
public LoadCalendar(IUserCalendar obj)
{
this.user = obj;
}
}
ViewCalendar 实现IUserCalendar:
public class Viewer : IUserCalendar
{
public string LoadCalendar()
{
return "Viewer Load Calendar Called";
}
}
使用代理类我正在为特定请求调用命令。 (这里我只为一位用户查看器显示一个请求LoadCalendar,但我有更多命令和更多用户)
我的客户有一个调用者对象,它为特定用户调用命令。
public class Client
{
public Client()
{ }
public string LoadCalendar(ICommand cmd)
{
Invoker invoker = new Invoker(cmd);
return invoker.execute();
}
}
现在我想测试客户端类,当它调用特定用户时,它应该返回正确的对象或消息。
[Test]
public void client_Load_Calendar_Administrator()
{
IUserCalendar calanedar = Substitute.For<IUserCalendar>();
ICommand cmd = Substitute.For<ICommand>(calanedar);
Client c = new Client();
c.LoadCalendar(cmd, calanedar).Returns(Arg.Any<string>());
}
我不知道我在哪里做错了,它抛出了一个错误。
NSubstitute.Exceptions.SubstituteException : 替换接口时无法提供构造函数参数。
非常感谢任何帮助。抱歉,问题太长了。
【问题讨论】:
-
感谢您编辑 Marc。如果你认识能回答这个问题的人,请转发给他。
标签: c# asp.net unit-testing mocking nsubstitute