[英]Using Nsubstitute for mocking but getting an error
我是单元测试的新手,所以请原谅我,如果我无法正确解释这个问题。 我正在读一本书“单元测试第二版的艺术”,并试图在我的项目中实施单元测试。 在使用模拟测试时(使用NSubstitute作为模拟框架),我目前陷入困境或困惑。
这是我的场景:
我有两个接口ICommand
和IUser
public interface ICommand
{
string execute();
}
public interface IUserCalendar
{
string LoadCalendar();
}
我有一个实现ICommand
的类LoadCalendar
:
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:替换接口时无法提供构造函数参数。
任何帮助都非常感谢。 对不起,对不起。
你得到的错误:
替换接口时无法提供构造函数参数。
告诉你到底出了什么问题。
你在这里传递构造函数参数:
ICommand cmd = Substitute.For<ICommand>(calanedar);
当然,接口永远不会有构造函数。 您正在尝试与ICommand接口进行交互,就好像它是您的具体LoadCalendar
实现一样。
此外,为了能够对一个类进行单元测试,你总是希望有一个默认的(无参数)构造函数。 许多模拟框架实际上需要这个。
在这种情况下,您应该测试具体类并模拟/替换它使用的类。
要么就是这样,要么只替换ICommand
使其返回预设(字符串)值。 然后,您可以继续验证使用命令的代码是否实际调用它和/或使用返回的值执行正确的操作。
为了显示:
[Test]
public void client_Load_Calendar_Administrator()
{
// You are substituting (mocking) the IUserCalendar here, so to test your command
// use the actual implementation
IUserCalendar calendar = Substitute.For<IUserCalendar>();
ICommand cmd = new LoadCalendar(calendar):
// Let the IUserCalendar.LoadCalendar() return a certain string
// Then Assert/Verify that cmd.Execute() returns that same string
}
这就是单元测试的重点:通过模拟所有依赖项来测试最小的功能。 否则它是一个集成测试。
测试您的客户:
[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
}
编辑:如果您感兴趣, NSubstitute中抛出此异常的方法 :
private void VerifyNoConstructorArgumentsGivenForInterface(object[] constructorArguments)
{
if (constructorArguments != null && constructorArguments.Length > 0)
{
throw new SubstituteException("Can not provide constructor arguments when substituting for an interface.");
}
}
他们对此非常清楚:无论如何都没有接口替换的构造函数参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.