Are my NUnit tests actually running correctly?

147 Views Asked by At

I'm trying to be a good developer and actually right some unit tests for some code I have written.

I am using NUnit with Ninject.MockingKernel.Moq and followed the documentation on https://github.com/ninject/ninject.mockingkernel/wiki/Examples. Here is an example of what I have been working with

[TestFixture]
public class MyUnitTest
{
    private readonly MoqMockingKernel _kernel;

    public MyUnitTest() 
    {
        _kernel = new MoqMockingKernel();
    }

    [SetUp]
    public void SetUp()
    {
        _kernel.Reset(); // Not really sure why this is included (something to do with caching...)
    }

    [Test]
    public void MyTest() 
    {
        var moqService = _kernel.GetMock<IMyService>();
        moqService.Setup(x=>x.MyMethod("With parameter")
                  .Returns(new MyObject {Id = 1, Name = "With parameter"});

        var service = _kernel.Get<IMyService>();
        service.MyMethod("With parameter");

        moqService.VerifyAll();
    }
}

Now, to my amazement this actually works but is it actually testing the logic in the code? Or is it saying when you return this method this is what will be returned?

I did a small test, MyMethod returns an object:

var method = service.MyMothod("With parameter");

Debugged the test and method.Id does in fact equal 1 so I'm 75% certain it's working but I thought it best to check with someone more knowledgeable than myself!

1

There are 1 best solutions below

1
On BEST ANSWER

If your goal is to test a IMyService that you implemented elsewhere, you are doing it wrong. What you are doing is creating a mock IMyService and testing that it is correctly mocked, which achieves not much.

You should use kernel.GetMock() if you need an IFoo to test your IMyService because your implementation of IMyService takes a IFoo as a parameter of its constructor (like it is done in the example that you linked).