Repository navigation
IMessengerExtensions.Send blocks unit testing #1113
Replies: 2 comments
|
I found an elegant working answer on Stack Overflow and I want to share it here for posterity's sake. Not gonna lie, my jaw dropped when I saw it work!
|
|
Hi Mike, The issue is caused by how Moq handles extension methods.
This creates a limitation when trying to express the verification using the public API. For a practical workaround, I would recommend testing the observable behavior rather than verifying the extension method itself. For example, use a real var messenger = new WeakReferenceMessenger();
var received = false;
var recipient = new object();
messenger.Register<NotificationMessage>(
recipient,
(r, message) => received = true);
// Execute the code under test using messenger.
Assert.True(received);This example assumes the code under test receives the Alternatively, if verifying interactions is a strict requirement, introduce an application-level messaging abstraction with a public, mockable method and verify that abstraction instead. This keeps the tests independent of CommunityToolkit's internal implementation details. The core distinction is that extension methods are static, while Moq verifies calls to interceptable interface or virtual members. Hope this helps! |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hello,
I'm migrating a legacy app from MvvmLight to CommunityToolkit. Most parts are easy to handle, but now all unit tests which check the IMessenger calls fail, because of the IMessengerExtensions which use the internal
Unittype.I use .NET Framework 4.8.x and Moq for unit testing.
There is a messenger send in a method:
And the unit tests for the method contains something like this:
The extension method
Send<TMessage>(this IMessenger messenger, TMessage message)uses the internal typeUnit, which I can't use in my units tests to see if a mock has the right invocations.dotnet/src/CommunityToolkit.Mvvm/Messaging/IMessengerExtensions.cs
Line 422 in 657c697
I can't write a working unit test:
Why is it not possible to use a public type in the extension method for the
TToken?The extension method should make it easy to use the Send method if you don't need different channels. However, the current implementation prevents this when I want to test my code. Or did I miss here something?
Thanks,
Mike
Update: It's not only the send method, all methods have the same problem.
All reactions