tags:

views:

132

answers:

1

Hi

I am using constructor injection pattern to insert my mocks with moq.

So I have something like this in my nunit test

property UserMock 
property IService // interface

public void PreSetup()
{
   UserMock = new UserMock;
   ITaskService = new Service(UserMock.object);

}

now I have a unit test method like this

public void TestSomething()
{
   UserMock.Setup(u => u.SomeMethod(It.IsAny<string>()));
}

Now I thought I always would have to do this after.

  public void TestSomething()
    {
       UserMock.Setup(u => u.SomeMethod(It.IsAny<string>()));
       ITaskService.User = UserMock.Object
    }

It seems I don't have to do this. Like my thinking was the object gets passed into the constructor and what ever is in it gets set into the "User" property in the TaskServiceClass.

So if I come at a later point and add something to a method it would not get set unless I reset the object.

It does not seem to be the case. So what am I not understanding?

Thanks

+1  A: 

This is all speculation: but UserMock.Object.SomeMethod probably calls into a custom method on its parent, as in UserMock.SomeMethod. At the very least the definition of SomeMethod is changed on UserMock.Object without creating a new object.

So passing in UserMock.Object to the constructor works fine, because if I'm right ITaskService holds a reference to UserMock.Object which holds a reference to UserMock, which is free to change its handling of SomeMethod without losing the connection you've established in PreSetup.

David Andres
Ah that sort of makes sense totally forgot about when you make objects a reference gets made and you can have different objects pointing to it.
chobo2
I've never actually used mocks in this manner, so I've haven't spent a minute thinking about it. Typically, I create a fresh mock and service within each test method, but that's borne out of habit and the need to be flexible on a per-test basis.
David Andres