Testing Custom Bootstrappers in Nancy - c#

So I have a CustomBootstrapper, which does a lot of application initialization, including IoC registration and Quartz scheduler setup. The modules also heavily rely on the SuperSimpleViewEngine.
Now I need to test this, using MSTest of course, and as everyone has probably figured out by now this is not going to work. The Nancy guys figured this out early, and have provided this workaround : https://github.com/NancyFx/Nancy/wiki/Nancy-Testing-View-Location which I assume works, because when I in my test case try to create an instance of my bootstrapper it fails miserably, because there are more than one RootPathProviders.
So the solution, it would seem is to use a ConfigurableBootStrapper. So I guess the only question is, how do I make sure that the ConfigurableBootStrapper is setup the same way as my CustomBootStraper?

var browser = new Browser(cfg =>
{
cfg.RootPathProvider<YourRootPathProvider>();
cfg.Module<YourModule>();
});

In your tests, create a test bootstrapper, which inherits from your custom one, then override only the functionality which breaks. Use that test bootstrapper for tests, assuming that your overrides are minimal.

Related

Win10 UWP, Prism/Unity and Unit Tests plus Class Libraries, silent failure

Basic layout is currently a simple app. Nothing fancy, I've got Views in the App.Views namespace and my ViewModels in the App.ViewModels namespace. The ViewModels are autowired to the Views through the XAML directive:
xmlns:prismMvvm="using:Prism.Windows.Mvvm"
prismMvvm:ViewModelLocator.AutoWireViewModel="True"
So, basically, this works. Then I wanted to leverage Unity's IoC / DependencyInjection for some unit tests.
The usual way would be to simply add a Windows 10 Unit Test App to the existing app and reference the latter in the Unit Test App.
This will crash upon executing the unit tests because it seems that you may not derive the App class from anything other but Application.
I.e. this works:
public sealed partial class App : Application
This does not:
public sealed partial class App : PrismUnityApplication
It's probably also not Prism's fault and something Microsoft has to fix on their end.
Now, the proposed workaround is to simply put whatever you want to unit test into a class library and reference this library from the unit test app. This works for unit testing. It also works for the Models.
My naive approach does not work, however, for the ViewModels. The ViewModel classes are still found under the App.ViewModels namespace, as before, just that they're now in a Class Library. I can access them programmatically in the main app just fine. But upon running the program, the AutoWiring silently fails without an error.
Even when I do something like this, it still does not work:
ViewModelLocationProvider.Register(typeof(MainPage).ToString(), () => new ViewModels.MainPageViewModel());
I'm not that experienced with the technologies involved yet so without an actual error I'm a bit at a loss.
edit: Just to add to the mystery - this code does work, regardless of whether the ViewModel resides in the main app or the class library:
var x = Container.Resolve(typeof(ExamplePageViewModel)) as ExamplePageViewModel;
You are correct, this is a limitation of UWP application testability in general. The testability of UWP apps is imperfect right now. In order to fix the first issue, you need to add the BindableAttribute to your application class:
[Bindable]
sealed partial class App : PrismUnityApplication
{
}
As far as pulling your Views/ViewModels out into separate assemblies, this issue is due to how UWP handles loading types form separate assemblies. None the less, this shouldn't stop you from testing your ViewModels. You can use a regular class library to test your ViewModel logic. You will mock your dependencies. You shouldn't be creating instances of your Views to test your ViewModels. So the ViewModelLocator becomes a non-issue.
We got the same issue as you, test silently failing.
when we looked at the Test output window we saw this:
App activation failed.
Failed to initialize client proxy: could not connect to test process.
Inside our [UnitTestApp], which inherits [PrismUnityApplication], we override [ConfigureContainer] method, and setup mocks on the container, instead of setting up real classes, i.e.
UnitTestApp.Current.Container.RegisterInstance(myMock.Object, new ContainerControlledLifetimeManager());
You may also have the Container setup in each test class' constructor
This way we got our test running without a silent failure.
It seemed that the silent failure was due to the container of the actual App class being called in the context of the UnitTestApp class - but I cannot confirm 100%

Testing static classes and methods in C# .NET

I'm relatively new to unit testing, and very new to C#, but I've been trying to test code that uses static classes with static methods, and it seems like I have to write huge amounts of boilerplate code in order to test, and that code would then also probably need to be tested.
For example: I'm using the System.Web.Security.Membership class, with a method ValidateUser on it. It seems like I need to create an interface IMembership containing the method ValidateUser, then create a class MembershipWrapper that implements IMembership, implementing the method ValidateUser and passing the arguments on to the actual Membership class. Then I need to have properties on my class that uses the Membership to reference the wrapper so that I can inject the dependency for a mock object during testing.
So to test 1 line of code that uses Membership, I've had to create an interface, and a class, and add a property and constructor code to my class. This seems wrong, so I must be getting something wrong. How should I be going about this testing? I've had a brief look at some frameworks/libraries that do dependency injection, but they still appear to require lots of boilerplate, or a very deep understanding of what's going on under the hood.
I don't see anything wrong in making your system loosely coupled. I believe you don't complain on creating constructor parameters and passing abstract dependencies to your classes. But instantiating dependencies in place looks so much easier, does it?
Also, as I pointed in comments, you can reuse wrappers later. So, that is not such useless work, as it seems from first glance.
You are on the right way, and think you are not testing single line of code, in this case you are writing important test to ensure that your code interacts with membership provider in the right way, this is not simple unit test rather "mock-based" integration test. I think it worth creating all these mocks and have covered by tests this part of application.
And yes, it seems overkill but no other way - either you use some helpers/libraries either wrap third-party static dependencies yourself.
I you're not happy taking the approach of constructor injection, you could look at using Ambient Context
You basically set up a default which will call System.Web.Security.Membership.ValidateUser
You then call the exposed method on the context in your code and you can now mock it for your tests
This allows you to write less setup code, but it also hides the fact that you have a dependency, which might be a problem in the future (depending on how you're reusing code)
If you're using VS2012, you can always use Shims in Microsoft Fakes for static calls (or .Net library calls too).
http://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/hh549176.aspx

Moq - Tests run ok when executed independently, but fail when executed in a row

We are using Moq to perform some unit tests, and there's some strange behaviour, perhaps it's some configuration issue that i'm missing.
basically, i have 2 tests (which call a windows workflow, which calls custom activities that call a method using Invoke. i don't know if this helps but i want to give as much info as i can). The tests run OK when executed alone, but if I execute them in a same run, the first one passes and the second fails (doesn't matter if i change the order of them, the 2nd one always fails)
The mock is recreated every time, loaded using Unity. ex :
MockProcessConfigurator = MockFactory.Create<IProcessConfigurator>();
MockProcessConfigurator.Setup(x => x.MyMethod(It.IsAny<Order>()));
[...]
InversionOfControl.Instance.Register<IProcessConfigurator>(MockProcessConfigurator .Object)
The invoked call (WF custom activity) is
var invoker = new WorkflowInvoker(new MyWorkflow());
invoker.Invoke(inputParameter);
The call (Invoked call) is
MyModuleService.ProcessConfigurator.MyMethod(inputOrder);
when debugging, i see that the ProcessConfigurator is always mocked.
The call that fails in the test is something as simple as this :
MockEnvironment.MockProcessConfigurator.Verify(x => x.MyMethod(It.IsAny<Order>()), Times.Exactly(1));
When debugging, the method is actually called everytime, so i suspect that there's something worng with the mock instance. I'm a bit lost here, because things seem to be implemented correctly, but for some reason when they're run one after the other, there's a problem
This type of error commonly occurs when the two tests share something.
For example, you set up your mock with an expectation that a method will be called 1 time in your test setup, and then two tests each call that method 1 time - your expectation will fail because it has now been called 2 times.
This suggests that you should be moving the set up of expectations into each test.
A generic troubleshooting for this type of problem is to try to isolate the dependency between the two test.
Move any setup-code to inside the tests.
Move any tear-down code to inside the tests.
Move any field initializers to inside the tests. (Those are only run once per fixture!)
This should make both your test pass when run together. When you got the green-lights, you can start moving out duplicated stuff again to initializers/setup one piece at the time, running the tests after each change you make.
You should be able to learn what is causing this coupling between the tests. Good luck!
Thought I'd add an additional situation and solution I just came across:
If you are running tests from two separate projects at the same time and each project is using a different version of Moq, this same problem can happen.
For me, I had TestProjectA using Moq 4.2.14 and TestProjectB using Moq 4.2.15 on accident (courtesy of Nuget). When running a test from A and a test from B simultaneously, the first test succeeded and the second silently failed.
Adjusting both projects to use the same version solved the issue.
To expand on the answer Sohnee gave, I would check my setup/teardown methods to make sure you're tidying everything up properly. I've had similar issues when running tests in bulk and not having tidied up my mock objects.
I don't know if this is relevant, but MockFactory.Create seems odd. I normally create mocks as follows:
var mockProcessConfigurator = new Mock<IProcessConfigurator>();
When using a MockFactory (which I never have needed), you would normally create an instance of it. From the moq QuickStart:
var factory = new MockFactory(MockBehavior.Strict) { DefaultValue = DefaultValue.Mock };
Calling a static method on MockFactory seems to defeat the purpose. If you have a nonstandard naming convention where MockFactory is actually a variable of type MockFactory, that's probably not your issue (but will be a constant source of confusion). If MockFactory is a property of your test class, insure that it is recreated on SetUp.
If possible I would eliminate the factory, as it is a potential source of shared state.
EDIT: As an aside, WorkflowInvoker.Invoke takes an Activity as a parameter. Rather than creating an entire workflow to test a custom activity, you can just pass an instance of the custom activity. If that's what you want to test, it keeps your unit test more focused.

How to easily tell if Ninject can resolve a class

I'm introducing Ninject into a large mess of a existing project. I want to write a diagnostic test to make sure that all of the classes Ninject will end up creating can actually BE resolved by Ninject...without actually creating any of them.
The reason I want to avoid the actual construction is that many of these classes have a tendency to start up database operations in their constructors (sigh yes I know). Otherwise I would just run them all through Get<T> with a try/catch
There's a CanResolve extension on IResolutionRoot (i.e., you can use it against Kernel if you have the right usings in place). There's a CreateRequest that you use to create the request. Have a look in the sources and tests if you need an example or any deeper information.
I know this is an old post but it was the first one I found when searching for how to find if a class can be resolved by Ninject without actually calling get() and risking an exception.
Ninject version 3.0.2 have a method CanResolve which returns a boolean:
kernel.CanResolve<T>()
I got 3.0.2 from nuget but its currently market unstable (Ninject.3.0.2-unstable-9037) so I'm not sure if I use this in production just yet.

Is it possible to virtualize a console application's disk access when shelled out from a C# application

I've got application A which runs application B as a console app. I'd like to write unit tests as part of application A which validate the input to/output from application B, but application B uses hard coded paths to look for some of its inputs. I'd like to be able to run the application, but intercept the call to read from c:\wherever\whatever.txt and provide the contents of that file myself.
Any frameworks or pieces which can do this for me?
This requires patching the Win32 CreateFile API function. Which is merely technically possible with Detours from Microsoft Research. Which requires unmanaged C or C++.
Tackle this problem at the source, having hard-coded path names in source code is unreasonable.
This is almost impossible!! I say almost because it is possible to intercept calls in the CLR but it is black magic and not recommended unless you are a CLR developer - perhaps a few hundred people in the world.
You can make the hard-coded paths as command line parameters and solve your problem this way.
You could include application B as a reference in application A, and then use Mocking frameworks to change the behaviour of B's methods or properties when calling it's API directly. This is the same process used for unit tests when setting up expectations on dependencies. There are limitations that generally this only works if the object in question is an interface, or contains vi
rtual (overridable) methods/properties. The solution may also be dependent on being able inject a dependency into Bs API, which may or may not be possible depending on the scenario.
Moq, Rhino Mocks. and TypeMock all provide this functionality. Here's a quick example of Moq to override the behaviour of a GetPath method with an alternative value:
// create a mocked version of a class and setup an expectation
var appBClassMoq = new Mock<AppBClass>();
appBClassMoq.SetUp(o => o.GetPath()).Returns("C:\MyNewPath");
// get the mocked instance
var appBClass = appBClassMoq.Object;
// run some code, when it hits GetPath() it will return the mock value
appBClass.SomeMethodThatCallsGetPath();

Categories

Resources