user1469452
user1469452

Reputation: 49

using NMock3 in c#, the mock throws expection even when I am not telling it to throw

I have seen a lot posts explaining how to use NMock to expect an exception. But that is not what i want to know. In my case, i am testing the happy path. But looks like the NMock is throwing exceptions as long as the method called on the mock is called within a try/catch. So suppose I have a method in the class i am testing:

class MyClass
{
    public MyClass(some_type obj)
    {
        m_member = obj;
    }

    public void Func()
    {
        try
        {
            m_member.some_function()
        }
        catch (System.Exception e)
        {
            // do something
        }
    }

    private some_type m_member;
}

In the unit test for this class, I have a test for this Func in MyClass to test the happy path:

[Test]
public void TestFunc()
{
    MockFactory mock_factory = new MockFactory();
    Mock<some_type> mock = mock_facoty.CreateMock<some_type>();
    MyClass uut = new MyClass(); 

    mock.Expects.One.MethodWith(_ => _.some_function());
    uut.Func();

    mock_facoty.VerifyAllExpectationsHaveBeenMet();
    mock_facoty.ClearExpectations();
}

This unit test keeps failing. If I remove the try/catch in the code and just do (line 8 - 18):

    public void Func()
    {
        //try
        //{
            m_member.some_function()
        //}
        //catch (System.Exception e)
        //{
        //    // do something
        //}
    }

This test will work fine.

Does anyone have an idea as to why is this happening? and how could I make this work? Thank you very much!

Upvotes: 1

Views: 1147

Answers (1)

Simon C
Simon C

Reputation: 9508

You are not actually using your mocked object, you are creating the concrete (real) some_type object in your MyClass constructor with the new statement.

I would suggest changing your MyClass class to accept the some_type object as a constructor parameter:

public MyClass(some_type thetype)
{
    m_member = thetype;
}

Then, in your test method, pass the mocked object into the ctor:

MockFactory mock_factory = new MockFactory();
Mock<some_type> mock = mock_factory.CreateMock<some_type>();
MyClass uut = new MyClass(mock.MockObject);

That will mean that your MyClass instance will actually use the mocked object, and then you can verify against it...

If you can't change your constructor to have a required parameter all the time, you could use a poor man's dependency injection (not recommended but might be necessary):

public MyClass() : this(new some_type()) {}

public MyClass(some_type thetype)
{
    m_member = thetype;
}

Upvotes: 1

Related Questions