how to verify that a method was called with an argument of a specific type
Asked Answered
D

1

15

I need to verify that a method was called with an object of a specific type

this is the interface with the method that I want to test that it was called:

interface IPlayer
{
   void Send(object message);
}

the test:

var player1 = A.Fake<IPlayer>();
room.AddPlayer(player1);

room.DoSomething();

A.CallTo(() => player1.Send(A<Type1>.Ignored)).MustHaveHappened();

since there are multiple calls to player1.Send with many different objects I get InvalidCastException

anybody knows how to do this properly ?

Dorsad answered 19/7, 2012 at 15:48 Comment(0)
S
16

This is by design, what you're trying to do is actually:

A.CallTo(() => player1.Send(A<object>.That.IsInstanceOf(typeof(MessageType)))).MustHaveHappened();

The type specified in A<?> should always be the exact parameter type the method takes. I actually did consider changing it so that you could constrain the type the way you propose and if I remember correctly the main reason (but I think there were other reasons too) was that it would be more fragile in cases where you introduce overloads.

For example, consider that you introduced the following overload on your IPlayer interface:

interface IPlayer
{
   void Send(object message);
   void Send(Type1 message);
}

Once you introduce this overload your test changes meaning.

Swithbert answered 23/7, 2012 at 7:39 Comment(1)
it's good the way you did it, I thought there should be something like this, just couldn't find it in the wikiDorsad

© 2022 - 2024 — McMap. All rights reserved.