ModuleBase Class w/ ICommandManager Registered Command - How to Unit Test?

Topics: Questions
Mar 3, 2014 at 6:32 PM
I'm still a bit new to following the MVVM pattern and implementing full unit testing so I'm struggling with how to create a unit test to make sure my module responds to a composite command. The class inherits from ModuleBase and calls RegisterCommand on the injected ICommandManager instance. I'm using the built in Fakes Microsoft provides within VS.NET 2013

How do I "fake" out the class to think that the command, it has subscribed to, has been invoked while performing my unit test on the class?
Mar 4, 2014 at 8:12 PM
A command is always something public on the VM. Whether it is registered on the CommandManager or not, it will always expose the ICommand interface to the outside world (a.k.a. public command). You can simply invoke vm.SomeCommand.Execute() to fake the execution of a command.
Mar 5, 2014 at 12:29 PM
Maybe I wasn't clear in my question. In this case, there is not ViewModel. The class under test is a module - that is, it inherits from Catel.Modules.ModuleBase and the command is one that is created during application start up - it is an application-wide command using the CommandManager and that this class under test needs to respond to when invoked at the top level. Within the class under test, the command is declared as private and registered like this:

// instantiate and register our local ShutdownCommand with the ICommandManager
_shutdownCommand = new Command<CancelEventArgs>(OnShutdownCommandExecute);
commandManager.RegisterCommand("ShutdownCommand", _shutdownCommand);

So what I want to test is that when the command is invoked that the module responds as expected. What I have ended up doing, in my unit test, is creating a CommandManager which creates a Command, instantiating my module and passing the "real" CommandManager and then using the CommandManager to invoke the command which, in turn, causes the module to react. Is that an okay approach in your opinion?
Mar 5, 2014 at 2:44 PM
This looks more like an integration test than a unit test. You are actually testing whether Catel correctly invokes all commands using the CommandManager. I think that is already covered by the unit tests in Catel and you only have to focus on whether the ShutdownCommand actually shuts down (but that is hard to test).

If you really feel that you need to test this, you can indeed create a custom instance of the CommandManager and pass that to the VM using dependency injection.