C# 使用Nsubstitute进行模拟但得到错误
我是单元测试新手,所以如果我不能正确解释这个问题,请原谅。我正在读一本书“单元测试的艺术第二版”,并试图在我的项目中实现单元测试。在使用mocking(使用NSubstitute作为mocking框架)进行测试时,我目前陷入了困境或困惑 以下是我的设想: 我有两个接口C# 使用Nsubstitute进行模拟但得到错误,c#,asp.net,unit-testing,mocking,nsubstitute,C#,Asp.net,Unit Testing,Mocking,Nsubstitute,我是单元测试新手,所以如果我不能正确解释这个问题,请原谅。我正在读一本书“单元测试的艺术第二版”,并试图在我的项目中实现单元测试。在使用mocking(使用NSubstitute作为mocking框架)进行测试时,我目前陷入了困境或困惑 以下是我的设想: 我有两个接口ICommand和IUser public interface ICommand { string execute(); } public interface IUserCalendar { st
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>());
}
[测试]
公共无效客户端\加载\日历\管理员()
{
IUserCalendar calanedar=替换.For();
ICommand cmd=替换为(calanedar);
客户机c=新客户机();
c、 LoadCalendar(cmd,calanedar).Returns(Arg.Any());
}
我不知道我哪里做错了,这是一个错误
NSSubstitute.Exceptions.SubstituteException:替换接口时无法提供构造函数参数
非常感谢您的帮助。很抱歉提出了这么长的问题。您遇到的错误: 替换接口时无法提供构造函数参数 告诉你到底是怎么回事 您正在此处传入构造函数参数:
ICommand cmd = Substitute.For<ICommand>(calanedar);
这就是单元测试的要点:通过模拟所有依赖项来测试最小的功能。否则这是一个集成测试
要测试您的客户端,请执行以下操作:
[Test]
public void client_Load_Calendar_Administrator()
{
ICommand cmd = Substitute.For<ICommand>();
Client c = new Client();
// Let your command return a certain string
// Then verify that your calendar returns that same string
}
他们对此非常清楚:不管发生什么,接口替换都没有构造函数参数。感谢编辑Marc。如果你知道谁能回答这个问题,请转发给他。你能给我提供更多关于集成测试的细节吗?非常感谢任何链接或任何书籍参考。此链接可能会让您感兴趣:。很抱歉,我不能为您提供一个工作代码示例-我不熟悉NSubstitute,我个人使用Moq。所以我不知道如何完成我试图解释的事情的确切语义。如果您愿意,我可以提供一个使用Moq和XUnit的更完整的示例?
[Test]
public void client_Load_Calendar_Administrator()
{
ICommand cmd = Substitute.For<ICommand>();
Client c = new Client();
// Let your command return a certain string
// Then verify that your calendar returns that same string
}
private void VerifyNoConstructorArgumentsGivenForInterface(object[] constructorArguments)
{
if (constructorArguments != null && constructorArguments.Length > 0)
{
throw new SubstituteException("Can not provide constructor arguments when substituting for an interface.");
}
}