Why should I favour stubs over mocks? - c#

I often read that one should avoid mocks and prefer stubs.
The Isolation Frameworks like FakeItEasy and NSubstitute make it most of the time really easy to mock or stub a dependency. Those frameworks themselves don't distinguish between stubs or mocks, but call them altogether Fakes or Substitutes. As far as I know in the early days of "Mocking" it was very hard to create mock objects, because using the cumbersome Record and Replay mechanism. But today it seems like there is no big difference anymore.
So why should I favor stubs over mocks? Why are mocks more brittle than stubs?

You shouldn't 'prefer' Stubs over Mocks; rather, you should select the right tool for the job:
Mocks for Commands, Stubs for Queries

At least with recent mocking tools, there is no point in bothering with stubs versus mocks. In practice, mock and stubs are the same thing when created by a mocking library. And this is how it should be.
With the mocking libraries available for Java (and for C#.NET too, if I am not mistaken), you can't create "just" a stub. You always get a mock object on which expectations can be verified.

Related

mocking in unit tests with dependency injection

I am wondering about the best way to make my system testable.
I am unsure of the best practice with DI and mocking.
If DI is facilitated by using interfaces should i build mock classes which implement the same interface as the real classes?
And then use these mock classes in my tests via DI?
I importing data into HDInsight. The data is taken from azure queues.
I want to mock/emulate both the queue and the hdinsight so my unit tests are fast and decoupled.
Should i use dependency injection in my tests or is moq sufficient, are these supposed to operate independently?
Mocks and Dependency Injection go hand in hand because without dependency injection, you would not be able to have your classes use the mocks instead of the real thing. What you don't need is a Dependency Injection Container (like Ninject for example). You can use it if you like, but if you did it right, you should be able to Unit-Test your classes by supplying all dependencies yourself.
Moq is sufficient.
Your tests use the mocks to help facilitate results. They are quick and easy to setup (once you are used to whatever mocking library you choose).
If you were to utilize a DI framework.. you would be tripling your workload. Not only are you manually stubbing out mocks.. but you are also then maintaining your DI configuration for your tests. This simply wouldn't fit nicely into any workflow.

Rhino Mocks: Verify all mocks in AAA syntax

When using the old Rhino Mocks record replay syntax, a MockRepository instance is created and all mocks from there. At the end of the unit test the method [MockRepository Instance].VerifyAll() is called to verify all the mocks.
With the current AAA syntax all mocks are created by the static methods on the MockRepository class. At the moment I did not find a better solution than verifying each mock object at the end of the test or on tear down. This is more error prone than the behaviour of the old syntax since sometimes a new mock instance is forgotten to verify.
How do you guys handle this, is there a better way to verify all existing mocks?
(...) is there a better way to verify all existing mocks?
The better way would be to test one thing at time. Perhaps Rhino's move away from verify all to explicit verification was done in such fashion - in order to promote testing single thing at time (and as a result, one verification is all you should ever need).
It's easy to realize that the need to verify multiple mocks probabaly comes from the fact that you want to check multiple behaviors at once (as in, single test). Note that this might be the result of non-optimal design choices few stages earlier, and you might take it (difficulty to write a test) as a warning sign.
At ayende's Rhino Mocks 3.5 guide page, you won't find a single example where two or mocks are used in one test.
On the mock and multiple stubs issue
You use stub to setup environment/requirements, not to verify your code. You never verify stub (like, whether some method was called or properties have certain values). Stub is essentially read-only component used by code you test. As a result of this distinction, stub will never make your test fail, whereas mock can certainly do so. This is why you can see multiple stubs in Rhino example, but always one mock.

Unit Testing in CSLA? How? What?

Does anyone have an example of unit testing in CSLA. I find it difficult to implement TDD with this framework and was wondering if there is any simple ways of doing this. Is there any other Mock Framework I could use besides TypeMock Isolator that is for free to build my test object? Please if you have any suggestions and samples/examples, I would be delighted? Thank you.
I'm not sure if I'm telling you some new information, but from CSLA 4 it's easier to unit test your custom BusinessRules and if you are using repositories as your data layer, you can mock the repositories to test the business objects together with the front end using them. Just remember that business objects aren't much more then a bunch of objects with properties where you should use Business Rules to implement business logic. Those Business Rules are just classes you can unit test without a problem.
It all depends on how your infrastructure is. Are you using a IoC pattern?
Which version of CSLA are you using?
Are you using the CSLA ObjectFactory's?
If you use CSLA as it should be used you'll have static factory methods and you have a non-public constructor. If you still want to unit test those properties inside the BusinessObjects you can choose out of some options.
If you use IoC for the datalayer (repositories) then you can mock those and test the business objects by configuring the IoC with mocks and stubs and in the testmethod call the factory methods and do your test.
If you don't use IoC, you might be lucky if you went for the CSLA ObjectFactory solution--there you can use mocks and stubs.
If you don't use IoC and didn't go for the ObjectFactory, you can't unit test the business objects that easily. But it's still possible by registering a custom DataPortal. Inside the DataPortal you can use reflection to construct the business object and resolve some mock/stub for that specific business object. It's not easy, but it's doable.
Sorry that I don't have any examples.

Why do we need mocking frameworks?

I have worked with code which had NUnit test written. But, I have never worked with mocking frameworks. What are they? I understand dependency injection and how it helps to improve the testability. I mean all dependencies can be mocked while unit testing. But, then why do we need mocking frameworks? Can't we simply create mock objects and provide dependencies. Am I missing something here?
Thanks.
It makes mocking easier
They usually
allow you to express testable
assertions that refer to the
interaction between objects.
Here you have an example:
var extension = MockRepository
.GenerateMock<IContextExtension<StandardContext>>();
var ctx = new StandardContext();
ctx.AddExtension(extension);
extension.AssertWasCalled(
e=>e.Attach(null),
o=>o.Constraints(Is.Equal(ctx)));
You can see that I explicitly test that the Attach method of the IContextExtension was called and that the input parameter was said context object. It would make my test fail if that did not happen.
You can create mock objects by hand and use them during testing using Dependency Injection frameworks...but letting a mocking framework generate your mock objects for you saves time.
As always, if using the framework adds too much complexity to be useful then don't use it.
Sometimes when working with third-party libraries, or even working with some aspects of the .NET framework, it is extremely difficult to write tests for some situations - for example, an HttpContext, or a Sharepoint object. Creating mock objects for those can become very cumbersome, so mocking frameworks take care of the basics so we can spend our time focusing on what makes our applications unique.
Using a mocking framework can be a much more lightweight and simple solution to provide mocks than actually creating a mock object for every object you want to mock.
For example, mocking frameworks are especially useful to do things like verify that a call was made (or even how many times that call was made). Making your own mock objects to check behaviors like this (while mocking behavior is a topic in itself) is tedious, and yet another place for you to introduce a bug.
Check out Rhino Mocks for an example of how powerful a mocking framework can be.
Mock objects take the place of any large/complex/external objects your code needs access to in order to run.
They are beneficial for a few reasons:
Your tests are meant to run fast and easily. If your code depends on, say, a database connection then you would need to have a fully configured and populated database running in order to run your tests. This can get annoying, so you create a replace - a "mock" - of the database connection object that just simulates the database.
You can control exactly what output comes out of the Mock objects and can therefore use them as controllable data sources to your tests.
You can create the mock before you create the real object in order to refine its interface. This is useful in Test-driven Development.
The only reason to use a mocking library is that it makes mocking easier.
Sure, you can do it all without the library, and that is fine if it's simple, but as soon as they start getting complicated, libraries are much easier.
Think of this in terms of sorting algorithms, sure anyone can write one, but why? If the code already exists and is simple to call... why not use it?
You certainly can mock your dependencies manually, but with a framework it takes a lot of the tedious work away. Also the assertions usually available make it worth it to learn.
Mocking frameworks allow you to isolate units of code that you wish to test from that code's dependencies. They also allow you to simulate various behaviors of your code's dependencies in a test environment that might be difficult to setup or reproduce otherwise.
For example if I have a class A containing business rules and logic that I wish to test, but this class A depends on a data-access classes, other business classes, even u/i classes, etc., these other classes can be mocked to perform in a certain manner (or in no manner at all in the case of loose mock behavior) to test the logic within your class A based on every imaginable way that these other classes could conceivably behave in a production environment.
To give a deeper example, suppose that your class A invokes a method on a data access class such as
public bool IsOrderOnHold(int orderNumber) {}
then a mock of that data access class could be setup to return true every time or to return false every time, to test how your class A responds to such circumstances.
I'd claim you don't. Writing test doubles isn't a large chore in 9 times out of 10. Most of the time it's done almost entirely automatically by just asking resharper to implement an interface for you and then you just add the minor detail needed for this double (because you aren't doing a bunch of logic and creating these intricate super test doubles, right? Right?)
"But why would I want my test project bloated with a bunch of test doubles" you may ask. Well you shouldn't. the DRY principle holds for tests as well. Create GOOD test doubles that are reusable and have descriptive names. This makes your tests more readable too.
One thing it DOES make harder is to over-use test doubles. I tend to agree with Roy Osherove and Uncle Bob, you really don't want to create a mock object with some special configuration all that often. This is in itself a design smell. Using a framework it's soooo easy to just use test doubles with intricate logic in just about every test and in the end you find that you haven't really tested your production code, you have merely tested the god-awful frankenstein's monsteresque mess of mocks containing mocks containing more mocks. You'll never "accidentally" do this if you write your own doubles.
Of course, someone will point out that there are times when you "have" to use a framework, not doing so would be plain stupid. Sure, there are cases like that. But you probably don't have that case. Most people don't, and only for a small part of the code, or the code itself is really bad.
I'd recommend anyone (ESPECIALLY a beginner) to stay away from frameworks and learn how to get by without them, and then later when they feel that they really have to they can use whatever framework they think is the most suitable, but by then it'll be an informed desicion and they'll be far less likely to abuse the framework to create bad code.
Well mocking frameworks make my life much easier and less tedious so I can spend time on actually writing code. Take for instance Mockito (in the Java world)
//mock creation
List mockedList = mock(List.class);
//using mock object
mockedList.add("one");
mockedList.clear();
//verification
verify(mockedList).add("one");
verify(mockedList).clear();
//stubbing using built-in anyInt() argument matcher
when(mockedList.get(anyInt())).thenReturn("element");
//stubbing using hamcrest (let's say isValid() returns your own hamcrest matcher):
when(mockedList.contains(argThat(isValid()))).thenReturn("element");
//following prints "element"
System.out.println(mockedList.get(999));
Though this is a contrived example if you replace List.class with MyComplex.class then the value of having a mocking framework becomes evident. You could write your own or do without but why would you want to go that route.
I first grok'd why I needed a mocking framework when I compared writing test doubles by hand for a set of unit tests (each test needed slightly different behaviour so I was creating subclasses of a base fake type for each test) with using something like RhinoMocks or Moq to do the same work.
Simply put it was much faster to use a framework to generate all of the fake objects I needed rather than writing (and debugging) my own fakes by hand.

How to mock or stub a .netTiers generated DataRepository object

I am using Rhino mocks for unit test mocking of objects. Our DAL uses codesmith to generate code from .netTiers templates, which creates these DataRepository classes that contain all the methods for CRUD type transaction to the datasource. In unit testing, I am trying to mock this data repository object which has no interface class to use as a stub.
In Brief, has anyone successfully used Rhino mocks to mock a .netTiers generated DataRepository, avoiding the need for a test database and real transactions against the datasource that needs to be tore down at the end??
I've been pondering this one for a while, as no one has stepped up and written a mock DataRepository implementation for netTiers yet (to my knowledge).
As I don't care too much for the record-replay steps of TypeMock and RhinoMocks, I've opted for the newer Moq, which will happily mock either the DataRepository classes or the Service layer calls themselves with minimal hassle.
Assuming you're on .NET 3.5, I'd recommend it.
In short, Rhino can only mock types that are either interfaces or non-sealed classes. And then, you can only stub methods that are virtual or abstract.
If your goal is to substitute a DataRepository with a mock implementation I think you will have to look into more advanced mocking frameworks like TypeMock.
If you're in control of the CS templates, another option would be to use the templates to also generate mock DataRepository implementations.

Categories

Resources