Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nsubstitute Calls Method in When even though there is DoNotCallBase

I am partially mocking a class that has these two methods:

public void EmitTo(string connectionId, ChatMessage message)
{
    Clients.Client(connectionId).broadcastMessage(message.User.UserName, message.Message);
}

public virtual void Broadcast(ChatMessage message)
{
    Clients.All.broadcastMessage(message.User.UserName, message.Message);
}

In my test [SetUp] I have these calls:

hub = Substitute.ForPartsOf<ChatHub>(myMockedClient, context, groupManager);
hub.When(x => x.Broadcast(Arg.Any<ChatMessage>())).DoNotCallBase();
hub.When(x => x.EmitTo(Arg.Any<string>(), Arg.Any<ChatMessage>())).DoNotCallBase();

I have no issues with the Broadcast call on this line or later on when I call the method (they do not do anything as expected) but oddly my third line throws an error:

System.ArgumentException : Argument cannot be null or empty Parameter name: connectionId

I am a bit lost as I did the exact same thing for both methods and get a different behaviour, why does my when method call the EmitTo?

like image 790
Lomithrani Avatar asked May 22 '15 10:05

Lomithrani


1 Answers

NSubstitute like most mocking frameworks can only intercept calls to virtual methods. It is able to stop the call to Broadcast, because it is virtual. You need to make EmitTo virtual if you want to stop it being called. It needs to be:

public virtual void EmitTo(string connectionId, ChatMessage message)
{
    Clients.Client(connectionId).broadcastMessage(message.User.UserName, message.Message);
}
like image 134
forsvarir Avatar answered Oct 18 '22 20:10

forsvarir