Nunit testing with Mock. Instance of Interface

Alex picture Alex · Jan 12, 2017 · Viewed 23.2k times · Source

I have the following (simplified) code.

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);
         }
     }
}

and SimpleInjector is used to inject the dependency between _service and its implementation class, like this:

public static void Register(Container container)
{
    container.Register<IService, Service>();
}

As a note, injection and unit testing are new to me so I do not fully understand them, but am learning.

If I run the application through Swagger, all is working fine.

As a note, the Register function is called when I run the application through Swagger.

Now, I am trying to setup some unit tests using NUnit, and am Mocking the IService object like this:

var Service = new Mock<IService>();
Controller _controller = new Controller(Service.Object);
_controller.Create(new MyObject object());

which seems to be correct to me so far - although I am not sure?

The problem is that for the unit test, result is always null - I think the is because there is a problem with my Mock of the interface - it does not seem to be finding the method - it never steps into it and does not show up int he debugger.

As a note, for the unit test, the Register method does not get called. I did try calling it to register the dependency, but it does not help.

As I said above, this is all new to me and I am on the edge of my understanding on all of this.

I am out of ideas and do not know where to look from here, so any help would be greatly appreciated.

EDIT:

The original question had the following:

public async Task<IHttpActionResult> Create(string content)

which I have updated to:

public async Task<IHttpActionResult> Create(MyObject object)

Can anyone advise how I can pass in a generic reference to MyObject on the setup, without having to make an instance of this class.

So basically I want to tell it that an instance of this class will be passed in, without creating that instance.

I have tried the following:

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

but it says cannot convert MethodGroup to MyObject

and here is the definition of IService:

public interface IService
{
      IdentityResult method(ApplicationUser user, UserLoginInfo login);
}

Answer

ganeshran picture ganeshran · Jan 12, 2017

The setup method has to be called on the Mock object.

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