chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
Hi,

I've come across the following which I'm struggling to figure out. I'd like to set an expectation to check that a method is called with parameters, which include a new instance of an object that gets created in the class under test:

public class ClassUnderTest
{
    public static T MethodUnderTest<T>(bool aBool) where T:new()
    {
        T newInstance = new T();
        if(aBool)
            AnotherClass.StaticMethod("aString", newInstance);
        else
            AnotherClass.StaticMethod("anotherString", newInstance);
    }
}


In this case, I'm trying to test that AnotherClass.StaticMethod gets called with the correct string parameter, depending on "aBool". So:

[Test]
public void MyTest()
{
   MockManager.Init();
   Mock mockMyType = MockManager.MockAll(typeof (MyType));
   mockMyType.ExpectConstructor();

   Mock mockAnotherClass = MockManager.Mock(typeof(AnotherClass));
   mockAnotherClass.ExpectCall("StaticMethod").Args("aString", mockMyType.MockedInstance);
            
   MyType actual = ClassUnderTest.MethodUnderTest<MyType>(true);
   MockManager.Verify(); 
}


This test fails, because mockMyType.MockedInstance is null at the time I set the expectation for "StaticMethod" to be called. Is there a way around this?

Many thanks,
Nick
asked by zcrar70 (2.9k points)

2 Answers

0 votes
Hi,

I think I understand what you're trying to do, but you're going around it the wrong way.

First, the reason MockedInstance is null, because MockAll is used in the context of a future object. You have not called new yet, since it's inside the method, and therefore the mock controller was not attached to it, and that is why it's null.

Now that doesn't solve the problem.
From the example, I'm guessing you are trying to check the first argument, but you don't care about the second. (at least from the code, it doesn't make other sense, but please correct me if I'm wrong.) If that is the issue, you don't have to mock MyType at all. You just need to call:
mockAnotherClass.ExpectCall("StaticMethod").Args("aString", Check.IsAny());


By which you ignore the last argument.
Let me know if this works for you.
answered by gilz (14.5k points)
0 votes
Hi Gilz,

Thanks for the response - I was indeed trying to check the value of the first argument without caring too much about the second (apologies for not making this clearer in the first post), and your solution worked perfectly.

Many thanks -

Nick
answered by zcrar70 (2.9k points)
...