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
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Should this fail? Doesn't seem to fail - have I got my code wrong?

public class A
{
    public string B
    {
        get
        {
            return null; 
        }
    }
}


        [Test, VerifyMocks]
        public void Test()
        {
            using (RecordExpectations rec = RecorderManager.StartRecording())
            {
                A a = RecorderManager.CreateMockedObject<A>();
                string temp = a.B;
                rec.FailWhenCalled();
            }

            A aClass = new A();
            string b = aClass.B;
        }
asked by sebastianpatten (2.2k points)

2 Answers

0 votes
Hi
The problem here is that you are using RecorderManager.CreateMockedObject.
The call creates an instance of class A and mock the instance in one call.
Than in your code outside the recording block you create another instace
which is not mocked.

What you want to do here is mock a future instance.

try:
using (RecordExpectations rec = RecorderManager.StartRecording())
{    
    A a = new A(); //This will mock future instance
    string temp = a.B;
    rec.FailWhenCalled();
}


:idea: Usually you will use RecorderManager.CreateMockedObject outside
the recording block. This usfull when you have interfaces or abstract classes you need to mock.

:idea: The difference between Mocking future instance (as in the code above) and mocking current instance (as in the code you posted) confuses many.
I think that this post in our blog should clear things up.

Hope it helps. Please tell me if you have more questions.
answered by ohad (35.4k points)
0 votes
Great stuff - thanks.
answered by sebastianpatten (2.2k points)
...