0

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!

Matt
  • 2,691
  • 3
  • 22
  • 36
  • 3
    I have no experience with NUnit/Ninject mocking in specific, but shouldn't you have an `assert` clause to actually test what it is you want to test? – Jeroen Vannevel Jan 08 '14 at 22:56
  • moqService.VerifyAll() actually throws an exception thus failing the test. This is all very new to me - I've got a feeling that the way I have written the test is incorrect though. MyMethod is in fact adding something to the database and then returns the object created... But i've already said the expected object is to be returned. – Matt Jan 08 '14 at 23:07
  • Opsie, @GrantWinney answered that before I got a chance! – Matt Jan 08 '14 at 23:08

1 Answers1

0

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).

Sidoine
  • 310
  • 3
  • 9
  • I think I understand now - problem is I am using a repository pattern in my Data Access Layer - would I have to Mock all the repositories that are used within my service to test it correctly? – Matt Jan 30 '14 at 16:34