使用 Mock 进行 Nunit 测试。接口实例

Ale*_*lex 6 c# nunit moq mocking simple-injector

我有以下(简化的)代码。

public class Controller
{
     private readonly IService _service;

     public Controller(IService service)
     {
         _service = service;
     }

     public async Task<IHttpActionResult> Create(MyObject object)
     {
         var result = _service.method(object);
         if (!result.Succeeded)
         {
            return this.GetErrorResult(object);
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

而 SimpleInjector 用于注入 _service 与其实现类之间的依赖关系,如下所示:

public static void Register(Container container)
{
    container.Register<IService, Service>();
}
Run Code Online (Sandbox Code Playgroud)

请注意,注入和单元测试对我来说是新的,所以我不完全理解它们,但正在学习。

如果我通过 Swagger 运行应用程序,一切正常。

请注意,Register当我通过 Swagger 运行应用程序时会调用该函数。

现在,我正在尝试使用 NUnit 设置一些单元测试,并像这样模拟 IService 对象:

var Service = new Mock<IService>();
Controller _controller = new Controller(Service.Object);
_controller.Create(new MyObject object());
Run Code Online (Sandbox Code Playgroud)

到目前为止,这对我来说似乎是正确的 - 尽管我不确定?

问题是对于单元测试,result始终为空 - 我认为这是因为我的 Mock 接口存在问题 - 它似乎没有找到方法 - 它从不进入它并且没有显示 int他调试器。

请注意,对于单元测试,Register不会调用该方法。我确实尝试调用它来注册依赖项,但它没有帮助。

正如我上面所说,这对我来说是全新的,我对所有这些都处于理解的边缘。

我没有想法,不知道从哪里看,所以任何帮助将不胜感激。

编辑:

原来的问题有以下几点:

public async Task<IHttpActionResult> Create(string content)
Run Code Online (Sandbox Code Playgroud)

我已更新为:

public async Task<IHttpActionResult> Create(MyObject object)
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议我如何MyObject在设置中传递通用引用,而不必创建此类的实例。

所以基本上我想告诉它这个类的一个实例将被传入,而不创建那个实例。

我尝试了以下方法:

Service.Setup(x => x.method(It.IsAny<MyObject>())

but it says cannot convert MethodGroup to MyObject
Run Code Online (Sandbox Code Playgroud)

这是 IService 的定义:

public interface IService
{
      IdentityResult method(ApplicationUser user, UserLoginInfo login);
}
Run Code Online (Sandbox Code Playgroud)

gan*_*ran 5

必须在 Mock 对象上调用 setup 方法。

var Service = new Mock<IService>();
Service.Setup(x=>x.method("argument")).Returns(YourReturnObject)
Controller _controller = new Controller(Service.Object);
Run Code Online (Sandbox Code Playgroud)


Chr*_*ord 5

您需要配置该Mock对象以返回某些内容,IService.method如下所示:

var Service = new Mock<IService>();
Service.Setup(x => x.method(It.IsAny<string>())
    .Returns<string>(str => **whatever result you need**);
Run Code Online (Sandbox Code Playgroud)

添加实际IService定义后,您应该将调用更改Setup为:

Service.Setup(x => x.method(It.IsAny<ApplicationUser>(), It.IsAny<UserLoginInfo>())
    .Returns<ApplicationUser, UserLoginInfo>((user, login) => new IdentityResult(true));
Run Code Online (Sandbox Code Playgroud)