Search code examples
c#unit-testingrhino-mocks

Use Rhino Mocking to unit test delete functionality


I am using Rhino mocking for unit testing to test a method that deletes a transport.However I am unsure how to test it. Below is what I have but it is failing (Assert.AreEqual is failing as result comes back with an exception object reference not set to instance of an object )

    /// <summary>
   /// Test Case: to
   /// </summary>
    [TestMethod]
    public void Should_DeleteTransload()
    {
        //expect
        mockTransloaderRepository.Expect(r => r.GetOneAsync(x => x.Id == ostTransloader5.Id)).IgnoreArguments().Return(Task.FromResult(ostTransloader5));
        mockOstTransloaderService = MockRepository.GenerateMock<OstTransloaderService>(mockTransloaderRepository, mockAuditContext);
        mockTransloaderRepository.Expect(r => r.AddAsync(ostTransloader5)).IgnoreArguments().Return(Task.Run(() => true));
        mockTransloaderRepository.Expect(r => r.AddAsync(ostTransloader4)).IgnoreArguments().Return(Task.Run(() => true));
        List<OstTransloader> ostTransloaders = new List<OstTransloader>() { ostTransloader4 };

        mockTransloaderRepository.Expect(t => t.DeleteAsync(ostTransloader5)).IgnoreArguments().Return(Task.Run(() => true));
        ////act
        var result = mockOstTransloaderService.PurgeTransloadShipmentMaterial(transloadIds);
        //// assert
        Assert.IsNotNull(result);
        Assert.AreEqual(ostTransloaders, result);           

    }

How do I test that the correct transload has been deleted?


Solution

  • Two disclaimers: (1) I moved from Rhino Mocks to Moq years ago, so this is from memory. (2) I can't see your code under test, so I'm having to assume you're setting your mocks up correctly to match how the code works.

    You need to check whether the right call was made into the dependency. This is done using Verify. Add this to your assert section.

    mockTransloaderRepository.Verify(t => t.DeleteAsync(ostTransloader5));
    

    You can prove whether this is checking the right thing by changing the code under test to call DeleteAsync(null), which should make the test fail, and when you put it back, the test should pass.

    Incidentally, in Moq, I would also be suggesting using a Times.Once parameter, to ensure it was called exactly once, and I'm assuming Rhino Mocks has something similar, but I'm sorry, I don't know what that is.