Mocking Microsoft.Toolkit.Mvvm.IMessenger - mvvm

It seems that for some reason, Microsoft has created an interface for it's messenger and then gone and implemented the logic as extension methods on the interface itself.
Unfortunately, I cannot use this beautiful solution: http://agooddayforscience.blogspot.com/2017/08/mocking-extension-methods.html - because IMessenger extensions calls implemented code on Messenger with an internal type as argument.
Why would Microsoft go to such lengths to make unit testing hard? (If you know a good, technical reason for this, please comment with the answer. I am very curious).
I want to unit test the ViewModels, which injects IMessenger. So how do I do this?
My solution is: Wrap IMessenger in a wrapper with an interface and inject that instead.
Is there a simpler/better solution? (I want it to be easy to understand and maintain).

Moq is incredibly extensible, and provides an extension point for exactly this purpose. You can provide custom type matching logic by creating a type that implements ITypeMatcher. To match the IMessenger.Send signature, for instance:
[TypeMatcher]
public sealed class IsAnyToken : ITypeMatcher, IEquatable<IsAnyToken>
{
public bool Matches(Type typeArgument) => true;
public bool Equals(IsAnyToken? other) => throw new NotImplementedException();
}
You can use this to write Setup and Verify code exactly like It.IsAnyType:
mockMessenger.Setup(x => x.Send(It.IsAny<MyMessage>(), It.IsAny<IsAnyToken>());
...
mockMessenger.Verify(x => x.Send(It.IsAny<MyMessage>(), It.IsAny<IsAnyToken>(), Times.Once);

Wrapping the interface (as others have suggested) is certainly an answer, but I don't like the cognitive overhead of having two interfaces so I came up with this. It does use a bit of reflection, but I couldn't find any other way to get at that object.
Long story short, it manually builds the setup expression against the internal type:
// Compile error, because Unit is internal
mock.Setup(x => x.Send<MyMessage, Unit>(It.IsAny<MyMessage>(), default));
But reflection and expression trees can still give it to us:
private static Type UnitType { get; } = typeof(IMessenger).Assembly
.GetType("Microsoft.Toolkit.Mvvm.Messaging.Internals.Unit");
public static ISetup<IMessenger, TMessage> SetupMessage<TMessage>(this Mock<IMessenger> messenger,
Expression<Func<TMessage, bool>>? validation = null)
where TMessage : class
{
MethodInfo sendMethod = typeof(IMessenger).GetMethod(nameof(IMessenger.Send))
.MakeGenericMethod(typeof(TMessage), UnitType);
ParameterExpression parameter = Expression.Parameter(typeof(IMessenger));
Expression<Func<TMessage>> message = validation switch
{
null => () => It.IsAny<TMessage>(),
not null => () => It.Is(validation),
};
MethodCallExpression methodCall = Expression.Call(
parameter,
sendMethod,
message.Body,
Expression.Default(UnitType));
Type funcType = Expression.GetFuncType(typeof(IMessenger), typeof(TMessage));
Expression lambda = Expression.Lambda(funcType, methodCall, parameter);
return messenger.Setup((Expression<Func<IMessenger, TMessage>>) lambda);
}

Related

How to resolve generic type at runtime

I'm trying to build a command processor that can take any command that implements a marker interface (or maybe descends from a base class). The processor will handle the command that it is asked to process. However I'm struggling with resolving the true generic type as Resolve(Type) returns an object.
I'm not sure is how to cast this if at all possible?
public void Process(ICommand command)
{
var c = command.GetType();
var t = typeof(ICommandHandler<>).MakeGenericType(new[] { c });
var o = container.Resolve(t);
//((ICommandHandler)o).Handle(command); *** This doesn't work
}
The calling code would be something like this -
Dispatcher.Process(new SomeCommand(Guid.NewGuid(),"Param1",12345));
If you absolutely have to call the ICommandHandler<T>.Handle method and you have no other control over the design of the system, then reflection may be your only choice. There's no great way to deal with the switch from generic to non-generic.
Otherwise, you may have a couple of options.
First, if your Dispatcher.Process can be made generic, you can save all the casting.
public static class Dispatcher
{
public static void Process<T>(T command) where T : ICommand
{
var handler = container.Resolve<ICommandHandler<T>>();
handler.Handle(command);
}
}
This is a pretty common solution to a problem like this that I've seen out in the wild.
If you can't do that, then you may be able to make your ICommandHandler<T> interface implement a non-generic ICommandHandler base interface.
public interface ICommandHandler
{
void Handle(ICommand command);
}
public interface ICommandHandler<T> : ICommandHandler
{
void Handle(T command);
}
In this latter case you'd have to switch your strongly-typed command handler implementations to call the same internal logic for generic or basic handling or you'll get different handling based on the call, which would be bad:
public class SomeCommandHandler : ICommandHandler<SomeCommand>
{
public void Handle(ICommand command)
{
var castCommand = command as SomeCommand;
if(castCommand == null)
{
throw new NotSupportedException("Wrong command type.");
}
// Hand off to the strongly-typed version.
this.Handle(castCommand);
}
public void Handle(SomeCommand command)
{
// Here's the actual handling logic.
}
}
Then when you resolve the strongly-typed ICommandHandler<T> your cast down to ICommandHandler (as shown in your question's sample code) will work.
This is also a pretty common solution, but I've seen it more in systems that existed before generics were available where an updated API was being added.
However, in all cases here, the problem really isn't that Autofac is returning an object; it's a class/type design problem that affects any generic-to-non-generic conversion scenario.
Using Reflection - but is this the best way to approach this?
public void Process(Command command)
{
var c = command.GetType();
var ot = typeof(ICommandHandler<>);
var type = ot.MakeGenericType(new[] { c });
var mi = type.GetMethod("Handle");
var o = container.Resolve(type);
mi.Invoke(o, new object[] { command });
}

how to judge the abstract class with ICompilationUnit

I am working on the eclipse plugin development,so I find the api docs and google them,it only contains such method isClass() isInterface() with the ICompilationUnit,but I want to dig deep with the abstract class,the code like
public boolean isAbstract(ICompilationUnit icu) {
//TODO
}
can anybody help me?
First, you will need an instance of org.eclipse.jdt.core.IType, because one ICompilationUnit can contain several types. ICompilationUnit.getTypes() will provide you with list of all types in this unit. ICompilationUnit.findPrimaryType() will get you a primary type for this unit.
Your routine should look something like following:
public boolean isAbstract(ICompilationUnit icu) throws JavaModelException {
final IType type = icu.findPrimaryType();
return (type != null)
? Flags.isAbstract(type.getFlags())
: false;
}
where Flags is org.eclipse.jdt.core.Flags.

Can I use NUnit TestCase to test mocked repository and real repository

I would like to be able to run tests on my fake repository (that uses a list)
and my real repository (that uses a database) to make sure that both my mocked up version works as expected and my actual production repository works as expected. I thought the easiest way would be to use TestCase
private readonly StandardKernel _kernel = new StandardKernel();
private readonly IPersonRepository fakePersonRepository;
private readonly IPersonRepository realPersonRepository;
[Inject]
public PersonRepositoryTests()
{
realPersonRepository = _kernel.Get<IPersonRepository>();
_kernel = new StandardKernel(new TestModule());
fakePersonRepository = _kernel.Get<IPersonRepository>();
}
[TestCase(fakePersonRepository)]
[TestCase(realPersonRepository)]
public void CheckRepositoryIsEmptyOnStart(IPersonRepository personRepository)
{
if (personRepository == null)
{
throw new NullReferenceException("Person Repostory never Injected : is Null");
}
var records = personRepository.GetAllPeople();
Assert.AreEqual(0, records.Count());
}
but it asks for a constant expression.
Attributes are a compile-time decoration for an attribute, so anything that you put in a TestCase attribute has to be a constant that the compiler can resolve.
You can try something like this (untested):
[TestCase(typeof(FakePersonRespository))]
[TestCase(typeof(PersonRespository))]
public void CheckRepositoryIsEmptyOnStart(Type personRepoType)
{
// do some reflection based Activator.CreateInstance() stuff here
// to instantiate the incoming type
}
However, this gets a bit ugly because I imagine that your two different implementation might have different constructor arguments. Plus, you really don't want all that dynamic type instantiation code cluttering the test.
A possible solution might be something like this:
[TestCase("FakePersonRepository")]
[TestCase("TestPersonRepository")]
public void CheckRepositoryIsEmptyOnStart(string repoType)
{
// Write a helper class that accepts a string and returns a properly
// instantiated repo instance.
var repo = PersonRepoTestFactory.Create(repoType);
// your test here
}
Bottom line is, the test case attribute has to take a constant expression. But you can achieve the desired result by shoving the instantiation code into a factory.
You might look at the TestCaseSource attribute, though that may fail with the same error. Otherwise, you may have to settle for two separate tests, which both call a third method to handle all of the common test logic.

Reflection / C# typing errors when publishing an F# class implementing an interface

I have an interface written in C#, but when implementing it in F#, I noticed some oddities.
The F# class has to be cast to the interface before C# can consume it
After casting, WPF can't read it's properties (Bindings failed and SNOOP was unable to reflect on it)
I can wrap the object in C# code and everything works fine.
the interface
public interface IInterpret {
public string Name {get;}
public IEnumberable<Project> Interpret(string text);
}
The F# Class
type Interpreter()=
interface IInterpret with
member x.Name = "FParsec Based"
member x.Interpret(str) = Seq.empty
The code below fails to compile
The error is about Interpreter not implementing IInterpert
public ViewModel(){
IInterpret i = new FSharpLib.Interperter();
}
This is my current workaround
public class MyProxy: IInterpret{
private IInterpret _cover;
public MyProxy() {
_cover = new FSharpLib.Interperter() as IInterpret;
}
public string Name { get { return _cover.Name; } }
public IEnumerable<Project> Interpret(string text){
return _cover.Interpret(text);
}
}
Is there something I'm doing wrong with my F# class def, or is the proxy needed? I'm using the current VS2010 f#, not an out of band drop.
F# implements all interfaces explicitly. This means you must explicitly cast to the interface type.
I don't know a ton about WPF binding to explicit interfaces, but see if these
http://leecampbell.blogspot.com/2008/09/generic-binding-in-wpf-through-explicit.html
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/92a2a3ba-74a6-4c79-9c75-f42d232a4dbf
help? (I just found them Bing-ing for "wpf binding explicit interfaces".)
(Another alternative may be to do something like
type Interpreter()=
member x.Name = "FParsec Based"
member x.Interpret(str:string) = Seq.empty
interface IInterpret with
member x.Name = x.Name
member x.Interpret(str) = x.Interpret(str)
where you "explicitly implement the interface implicitly", if you pardon the confusing terminology.)

How do I simplify these NUNit tests?

These three tests are identical, except that they use a different static function to create a StartInfo instance. I have this pattern coming up all trough my testcode, and would love
to be be able to simplify this using [TestCase], or any other way that reduces boilerplate code. To the best of my knowledge I'm not allowed to use a delegate as a [TestCase] argument, and I'm hoping people here have creative ideas on how to make the code below more terse.
[Test]
public void ResponseHeadersWorkinPlatform1()
{
DoResponseHeadersWorkTest(Platform1StartInfo.CreateOneRunning);
}
[Test]
public void ResponseHeadersWorkinPlatform2()
{
DoResponseHeadersWorkTest(Platform2StartInfo.CreateOneRunning);
}
[Test]
public void ResponseHeadersWorkinPlatform3()
{
DoResponseHeadersWorkTest(Platform3StartInfo.CreateOneRunning);
}
void DoResponseHeadersWorkTest(Func<ScriptResource,StartInfo> startInfoCreator)
{
ScriptResource sr = ScriptResource.Default;
var process = startInfoCreator(sr).Start();
//assert some things here
}
Firstly, I don't think the original is too bad. It's only messy if your assertions are different from test case to test case.
Anyway, you can use a test case, but it can't be done via a standard [TestCase] attribute due to using more complicated types. Instead, you need to use a public IEnumerable<> as the data provider and then tag your test method with a [TestCaseSource] attribute.
Try something like:
public IEnumerable<Func<ScriptResource, StartInfo>> TestCases
{
get
{
yield return Platform1StartInfo.CreateOneRunning;
yield return Platform2StartInfo.CreateOneRunning;
yield return Platform3StartInfo.CreateOneRunning;
}
}
[TestCaseSource("TestCases")]
public void MyDataDrivenTest(Func<ScriptResource, StartInfo> startInfoCreator)
{
ScriptResource sr = ScriptResource.Default;
var process = startInfoCreator(sr);
// do asserts
}
}
This is a more concise version of the standard pattern of yielding TestCaseData instances containing the parameters. If you yield instances of TestCaseData you can add more information and behaviours to each test (like expected exceptions, descriptions and so forth), but it is slightly more verbose.
Part of the reason I really like this stuff is that you can make one method for your 'act' and one method for your 'assert', then mix and match them independently. E.g. my friend was doing something yesterday where he used two Actions to say ("when method Blah is called, this method on the ViewModel should be triggered"). Very terse and effective!
It looks good. Are you looking to add a factory maybe ? Or you could add these methods to a Action List(in test setup) and call first action delegate, second action delegate and third action delegate.