Ninject MockingKernel with Saboteurs - ninject

Is it possible to use MockingKernel so that it generates mock objects automatically that, if interacted with, will throw an exception (a.k.a, saboteurs)?
This is useful when you want to get an object with various dependencies, but you know your code should only be interacting with some of them. If you don't explicitly Bind a dependency (via ToMock, etc.), it should return an object that throws an exception the first time it is interacted with.
This is much better than waiting until the code finishes executing, then writing a bunch of checks to make sure you didn't call into a mock.
Does this already exist?

The answer provided above did not indicate how to setup the Ninject MockingKernel using MOQ so that the default behavior is Strict. For the benefit of others, here is what I found.
The Ninject.MockingKernel.Moq namespace provides the class NinjectSettingsExtensions with the methods SetMockBehavior() and GetMockBehavior() that allow you to specify which mocking behavior to use as the global default. I have NOT been able to find any way to override the default for an individual GetMock() request.
using Ninject;
using Ninject.MockingKernel.Moq;
var kernelSettings = new NinjectSettings();
kernelSettings.SetMockBehavior(MockBehavior.Strict);
using(var kernel = new MoqMockingKernel(kernelSettings))
{
var mockFoo = kernel.GetMock<IFoo>(); // mockFoo.Behavior == MockBehavior.Strict
}

I had been using NSubstitute's implementation of MockingKernel. NSubstitute doesn't really support a "strict" mode and you can't configure it through the NSubstituteMockingKernel class.
However, you can configure Moq to do strict mode. Best of all, the MoqMockingKernel class allows you to change the mock behavior globally. This way, any calls that aren't configured result in an exception being thrown.
This is exactly what I was looking for. The only pain was switching from NSubstitute to Moq.

Related

ByteBuddy - rebase already loaded class

I have the following code working in a SpringBoot application, and it does what's I'm expecting.
TypePool typePool = TypePool.Default.ofClassPath();
ByteBuddyAgent.install();
new ByteBuddy()
.rebase(typePool.describe("com.foo.Bar").resolve(), ClassFileLocator.ForClassLoader.ofClassPath())
.implement(typePool.describe("com.foo.SomeInterface").resolve())
.make()
.load(ClassLoader.getSystemClassLoader());
Its makes is so that the class com.foo.Bar implements the interface com.foo.SomeInterface (which has a default implementation)
I would like to . use the above code by referring to the class as Bar.class, not using the string representation of the name. But if I do that I get the following exception.
java.lang.UnsupportedOperationException: class redefinition failed: attempted to change superclass or interfaces
I believe due to the fact that it cause the class to be loaded, prior to the redefinition. I'm just now learning to use ByteBuddy.
I want to avoid some reflection at runtime, by adding the interface and an implementation using ByteBuddy. I've some other code that checks for this interface.
This is impossible, not because of Byte Buddy but no tool is allowed to do this on a regular VM. (There is the so-called dynamic code evolution VM which is capable of that).
If you want to avoid the problem, use redefine rather then rebase. Whenever you instrument a method, you do now however replace the original.
If this is not acceptable, have a look at the Advice class which you can use by the .visit-API to wrap logic around your original code without replacing it.

System.Collections.ObjectModel.ObservableCollection only partially implemented in Monotouch?

I'm consuming WCF services using the Silverlight 3 stubs and one parameter I need is a System.Collections.ObjectModel.ObservableCollection.
However the following code is throwing a NotImplementedException:
ItemType[] aItemTypes = ...;
ObservableCollection<ItemType> aTypes = null;
if(aItemTypes != null)
{
aTypes = new ObservableCollection<ItemType> (aItemTypes);
}
If I use a foreach loop to add all entries manually instead of using the constructor that takes an enumerable, it works. Is there a reason why the constructor is missing or was it just forgotten?
Is there a reason why the constructor is missing or was it just forgotten?
This sometimes occurs on Mono base class library source code when someone implement a type but does not need everything inside it. In such cases it's better to add stubs for the missing code since this:
allow compilation of existing code;
it avoid MissingMethodException at runtime, a NotImplementedException is easier to diagnose;
allow Mono's tooling, e.g. MoMA and Gendarme, to report the NotImplementedException on existing .NET code.
In this specific case I suspect that more tests were needed to see if the items being copied needed to trigger events (whgen adding them) or not.
The good news is that this method is implemented in Mono's GIT master. I'll look into backporting this into mono-2-10 branch so MonoTouch will get it in future releases.

Rhino mock a singleton class

I want to test my controller that depends on a hardware C# class, not an interface.
It's configured as a singleton and I just can't figure out how to RhinoMock it.
The hardware metadata (example) for the dependent class:
namespace Hardware.Client.Api
{
public class CHardwareManager
{
public static CHardwareManager GetInstance();
public string Connect(string clientId);
}
}
and in my code I want this something like this to return true, else I get an exception
if( !CHardwareManager.GetInstance().Connect("foo") )
I mock it using:
CHardwareManager mockHardwareMgr MockRepository.GenerateMock<CHardwareManager>();
But the Connect needs a GetInstance and the only combination I can get to "compile" is
mockHardwareMgr.Expect (x => x.Connected ).Return(true).Repeat.Any();
but it doesn't correctly mock, it throws an exception
but this complains about typing the GetInstance
mockHardwareMgr.Expect (x => x.GetInstance().Connected).Return(true).Repeat.Any();
So my problem - I think - is mocking a singleton. Then I have no idea how to make my controller use this mock since I don't pass the mock into the controller. It's a resource and namespace.
90% of my work requires external components I need to mock, most times I don't write the classes or interfaces, and I'm struggling to get them mocked and my code tested.
Any pointers would be welcome.
Thanks in advance (yes, I've been searching through SO and have not seen something like this. But then, maybe my search was not good.
The usual way to avoid problems with mocking external components is not to use them directly in your code. Instead, define an anti-corruption layer (usually through an interface that looks like your external component) and test your code using mocked implementation of this interface. After all, you're testing your own code, not the external one.
Even better way is to adjust this interface to your needs so it only exposes stuff that you actually need, not the whole API the external component provides (so it's actually an Adapter pattern).
External components are tested using different approaches: system testing, in which case you don't really mock them, you use the actual implementation.
Usually when you try to get Rhino Mocks to do something which feels unnatural and Rhino growls, this is a good sign that your approach is not the right one. Almost everything can be done using simple interface mocking.
As Igor said RhinoMocks (and most other free mocking frameworks, e.g. Moq) can only mock interfaces.
For mocking classes try (and pay) TypeMock.
For mocking singletons see my answer to:
How to Mock a Static Singleton?
Yes, I'm somewhat undermining the common understanding of what's deemed testable and thus "good" code. However I'm starting to resent answers like "You're doing it wrong. Make everything anew." for those answers don't solve the problem at hand.
No, this is not pointing at Igor, but at many others in similar threads, who answered "Singletons are unmockable. (Make everything anew.)".

Alternatives for the singleton pattern?

I have been a web developer for some time now using ASP.NET and C#, I want to try and increase my skills by using best practices.
I have a website. I want to load the settings once off, and just reference it where ever I need it. So I did some research and 50% of the developers seem to be using the singleton pattern to do this. And the other 50% of the developers are ant-singleton. They all hate singletons. They recommend dependency injection.
Why are singletons bad? What is best practice to load websites settings? Should they be loaded only once and referenced where needed? How would I go about doing this with dependency injection (I am new at this)? Are there any samples that someone could recommend for my scenario? And I also would like to see some unit test code for this (for my scenario).
Thanks
Brendan
Generally, I avoid singletons because they make it harder to unit test your application. Singletons are hard to mock up for unit tests precisely because of their nature -- you always get the same one, not one you can configure easily for a unit test. Configuration data -- strongly-typed configuration data, anyway -- is one exception I make, though. Typically configuration data is relatively static anyway and the alternative involves writing a fair amount of code to avoid the static classes the framework provides to access the web.config anyway.
There are a couple of different ways to use it that will still allow you to unit test you application. One way (maybe both ways, if your singleton doesn't lazily read the app.cofnig) is to have a default app.config file in your unit test project providing the defaults required for your tests. You can use reflection to replace any specific values as needed in your unit tests. Typically, I'd configure a private method that allows the private singleton instance to be deleted in test set up if I do make changes for particular tests.
Another way is to not actually use the singleton directly, but create an interface for it that the singleton class implements. You can use hand injection of the interface, defaulting to the singleton instance if the supplied value is null. This allows you to create a mock instance that you can pass to the class under test for your tests, but in your real code use the singleton instance. Essentially, every class that needs it maintains a private reference to the singleton instance and uses it. I like this way a little better, but since the singleton will be created you may still need the default app.config file, unless all of the values are lazily loaded.
public class Foo
{
private IAppConfiguration Configuration { get; set; }
public Foo() : this(null) { }
public Foo( IAppConfiguration config )
{
this.Configuration = config ?? AppConfiguration.Instance;
}
public void Bar()
{
var value = this.Config.SomeMaximum;
...
}
}
There's a good discussion of singleton patterns, and coding examples here... http://en.wikipedia.org/wiki/Singleton_pattern See also here... http://en.wikipedia.org/wiki/Dependency_injection
For some reason, singletons seem to divide programmers into strong pro- and anti- camps. Whatever the merits of the approach, if your colleagues are against it, it's probably best not to use one. If you're on your own, try it and see.
Design Patterns can be amazing things. Unfortunately, the singleton seems to stick out like a sore thumb and in many cases can be considered an anti-pattern (it promotes bad practices). Bizarely, the majority of developers will only know one design pattern, and that is the singleton.
Ideally your settings should be a member variable in a high level location, for example the application object which owns the webpages you are spawning. The pages can then ask the app for the settings, or the application can pass the settings as pages are constructed.
One way to approach this problem, is to flog it off as a DAL problem.
Whatever class / web page, etc. needs to use config settings should declare a dependency on an IConfigSettingsService (factory/repository/whatever-you-like-to-call-them).
private IConfigSettingsService _configSettingsService;
public WebPage(IConfigSettingsService configSettingsService)
{
_configSettingsService = configSettingsService;
}
So your class would get settings like this:
ConfigSettings _configSettings = _configSettingsService.GetTheOnlySettings();
the ConfigSettingsService implementation would have a dependency which is Dal class. How would that Dal populate the ConfigSettings object? Who cares.
Maybe it would populate a ConfigSettings from a database or .config xml file, every time.
Maybe it do that the first time but then populate a static _configSettings for subsequent calls.
Maybe it would get the settings from Redis. If something indicates the settings have changed then the dal, or something external, can update Redis. (This approach will be useful if you have more than one app using the settings.
Whatever it does, your only dependency is a non-singleton service interface. That is very easy to mock. In your tests you can have it return a ConfigSettings with whatever you want in it).
In reality it would more likely be MyPageBase which has the IConfigSettingsService dependency, but it could just as easily be a web service, windows service, MVC somewhatsit, or all of the above.

How can I avoid global state?

So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests. I believe it--my code is difficult to test right now. So how do I avoid global state?
The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments. For example, I have a static class named "Globals" with a static member called "DBConnectionString." When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString. I load file paths, server names, and other information in the Globals class.
Some of my functions rely on the global variables. So, when I test my functions, I have to remember to set certain globals first or else the tests will fail. I'd like to avoid this.
Is there a good way to manage state information? (Or am I understanding global state incorrectly?)
Dependency injection is what you're looking for. Rather than have those functions go out and look for their dependencies, inject the dependencies into the functions. That is, when you call the functions pass the data they want to them. That way it's easy to put a testing framework around a class because you can simply inject mock objects where appropriate.
It's hard to avoid some global state, but the best way to do this is to use factory classes at the highest level of your application, and everything below that very top level is based on dependency injection.
Two main benefits: one, testing is a heck of a lot easier, and two, your application is much more loosely coupled. You rely on being able to program against the interface of a class rather than its implementation.
Keep in mind if your tests involve actual resources such as databases or filesystems then what you are doing are integration tests rather than unit tests. Integration tests require some preliminary setup whereas unit tests should be able to run independently.
You could look into the use of a dependency injection framework such as Castle Windsor but for simple cases you may be able to take a middle of the road approach such as:
public interface ISettingsProvider
{
string ConnectionString { get; }
}
public class TestSettings : ISettingsProvider
{
public string ConnectionString { get { return "testdatabase"; } };
}
public class DataStuff
{
private ISettingsProvider settings;
public DataStuff(ISettingsProvider settings)
{
this.settings = settings;
}
public void DoSomething()
{
// use settings.ConnectionString
}
}
In reality you would most likely read from config files in your implementation. If you're up for it, a full blown DI framework with swappable configurations is the way to go but I think this is at least better than using Globals.ConnectionString.
Great first question.
The short answer: make sure your application is a function from ALL its inputs (including implicit ones) to its outputs.
The problem you're describing doesn't seem like global state. At least not mutable state. Rather, what you're describing seems like what is often referred to as "The Configuration Problem", and it has a number of solutions. If you're using Java, you may want to look into light-weight injection frameworks like Guice. In Scala, this is usually solved with implicits. In some languages, you will be able to load another program to configure your program at runtime. This is how we used to configure servers written in Smalltalk, and I use a window manager written in Haskell called Xmonad whose configuration file is just another Haskell program.
An example of dependency injection in an MVC setting, here goes:
index.php
$container = new Container();
include_file('container.php');
container.php
container.add("database.driver", "mysql");
container.add("database.name","app");
...
$container.add(new Database($container->get('database.driver', "database.name")), 'database');
$container.add(new Dao($container->get('database')), 'dao');
$container.add(new Service($container->get('dao')));
$container.add(new Controller($container->get('service')), 'controller');
$container.add(new FrontController(),'frontController');
index.php continues here:
$frontController = $container->get('frontController');
$controllerClass = $frontController->getController($_SERVER['request_uri']);
$controllerAction = $frontController->getAction($_SERVER['request_uri']);
$controller = $container->get('controller');
$controller->$action();
And there you have it, the controller depends on a service layer object which depends on
a dao(data access object) object which depends on a database object with depends on the
database driver, name etc