Rhino Mocks: Stub & Mocks. What is the difference - unit-testing

I'm using Rhino Mocks in my unit test.
I would like to know the difference between STUBS and MOCKS (mocks.Stub<T>() and mocks.StrictMock<T>()).

I think it had been asked before.
It is generally the same with the following differences:
Strict Mocks throw exceptions on each call which had not been expected
Dynamic Mocks accept unexpected calls und just return default values (eg. null)
Stubs are like dynamic mocks but have "property behaviour" turned on by default. This allows writing and reading properties like fields, but doesn't allow Stub, Expect nor AssertWasCalled on properties. This behaviour can also be configured on a normal Mock too. But for stubs it is the default.
Since Rhino changed to AAA syntax, it is discouraged to use Strict Mocks, since they make test code very hard to maintain.
Similar questions:
What are the differences between mocks and stubs on Rhino Mocks?
Rhino Mocks - Difference between GenerateStub<T> & GenerateMock<T>
I can't find the information about the Rhino implementation, so I don't mark this question as duplicate.

Related

How is Jmockit different from EasyMock? Which is better to use?

I have for long worked on EasyMocking in JUnits. I am pretty much comfortable with this but now I want to know how EasyMocks are different from Jmockits. I tried going through their documentation and I found out that the syntax is a bit different. But yet I could not figure out if there is any difference in their performances.
Can anyone help me figure out what are the points that make either of them better than the other? Is there any special element in JMockit that is not found in the other?
Thanks in advance...
There are many differences between JMockit and EasyMock/jMock/Mockito/PowerMock.
These are the major ones:
Support for integration testing: JMockit supports an out-of-container integration testing approach, similar to what the Spring Test module provides, but also supporting Java EE. The other mocking libraries only support isolated unit testing with mock objects.
A "faking" API (see also in xUnit Patterns), in addition to the mocking API. Each one of the other mocking libraries only have a mocking API.
Full support for "mocking", in addition to "mock objects". Other mocking libraries work with mock objects which they create and which need to be passed in somehow to the code under test. With EasyMock/jMock/Mockito, static methods, constructors, and "new-ed" objects cannot be mocked at all. PowerMock supports full mocking as well, but still focused on mock objects (specifically, new-ed objects must be "replaced" with mock objects through whenNew recording, while with JMockit a test can simply declare a #Mocked field).
Support for mocking/faking of final classes and methods. Only PowerMock also provides this support. Mockito recently added an "inline mock maker" which adds support for finals, but it's not active by default and may not be as reliable.
Support for mocking/faking of unspecificied subclasses and interface implementations (where the test only declares a base type to be mocked/faked).
In the mocking API, expectations on methods with multiple parameters can be recorded/verified with argument matchers (such as anyString, etc.) only for some parameters, while other mocking APIs require such matchers for every single parameter.
Also in the mocking API, expectations can be explicitly verified after the tested code was exercised, just like in Mockito. EasyMock/jMock do not support this verification model.
As for performance, mocking a type with JMockit (done through class redefinition) probably has a higher runtime overhead when compared to creating a mock object with EasyMock/jMock/Mockito (done through subclass definition), and lower when compared with PowerMock (done through class definition on a custom classloader). However, you should only notice the difference in performance if there is a lot of mocking being done, which most likely indicates overuse of mocking.
You can find a blog post about the differences between them (and also mockito!) here: http://www.baeldung.com/mockito-vs-easymock-vs-jmockit
While they all have different syntax and different ways of working, you should be able to achieve whatever you need in regards to mocking with either framework.

Mock framework vs MS Fakes frameworks

A bit confused on the differences of Mock frameworks like NMock vs the VS 2011 Fakes Framework.
Going through MSDN, what I understand is that Fakes allow you to mock your dependencies just like RhinoMock or NMock, however the approach is different, Fakes generates code to achive this functionality but Mocks framework does not. So is my understanding correct? Is Fakes just another Mock framework
Your question was about how the MS Fakes framework is different from NMock and it appears the other answers have resolved some of that, but here is some more information regarding how they are the same and how they are different. NMock is also similar to RhinoMocks and Moq, so I'm grouping them in with NMock.
There are 3 major differences I see right off between NMock/RhinoMocks/Moq and the MS Fakes Framework:
The MS fakes framework uses generated code, much like Accessors in prior versions of Visual Studio instead of generic types. When you want to use the fakes framework for a dependency, you add the assembly that contains the dependency to the references of the test project and then right-click on it to generate the test doubles (stubs or shims). Then when you are testing, you are actually using these generated classes instead. NMock uses generics to accomplish the same thing (i.e. IStudentRepository studentRepository = mocks.NewMock<IStudentRepository>()). In my opinion, the MS Fakes framework approach inhibits code navigation and refactoring from within the tests since you are actually working against a generated class, not your real interface.
The MS fakes framework supplies stubs and moles (shims), whereas NMock, RhinoMocks, and Moq all provide stubs and mocks. I really don't understand MS's decision to not include mocks and I am, personally not a fan of moles for reasons described below.
With the MS fakes framework, you supply an alternative implementation of the methods you want to stub. Within these alternate implementations, you can specify the return values and track information about how or if the method was called. With NMock, RhinoMocks and Moq, you generate a mock object and then use that object to specify stubbed return values or to track interactions (whether and how the methods were called). I find the MS fakes approach more complex and less expressive.
To clarify the difference in what the frameworks provide: NMock, RhinoMocks and Moq all provide two types of test doubles (stubs and mocks). The fakes framework provides stubs and moles (they call them shims), and unfortunately does not include mocks. In order to understand the differences and similarities between NMock and MS Fakes, it is helpful to understand what these different types of test doubles are:
Stubs: Stubs are used when you need to provide a values for methods or properties that will be asked of your test doubles by the method under test. For example, when my method under test calls the DoesStudentExist() method of the IStudentRepository test double, I want it to return true.
The idea of stubs in NMock and MS fakes is the same, but with NMock you would do something like this:
Stub.On(mockStudentRepository).Method("DoesStudentExist").Will(Return.Value(true));
And with MSFakes you would do somethign like this:
IStudentRepository studentRepository = new DataAccess.Fakes.StubIStudentRepository() // Generated by Fakes.
{
DoesStudentExistInt32 = (studentId) => { return new Student(); }
};
Notice in the MS Fakes example you create an entirely new implementation for the DoesStudentExist method (Note that it is called DoesStudentExistInt32 because the fakes framework appends the parameter data types to the method names when it generates the stub objects, I think this obscures the clarity of the tests). To be honest the NMock implementation also bugs me because it uses a string to identify the method name. (Forgive me if I've misunderstood how NMock is intended to be used.) This approach really inhibits refactoring and I'd highly recommend RhinoMocks or Moq over NMock for this reason.
Mocks: Mocks are used to verify interaction between your method under test and its dependencies. With NMock, you do this by setting expectations similar to this:
Expect.Once.On(mockStudentRepository).Method("Find").With(123);
This is another reason why I'd prefer RhinoMocks and Moq over NMock, NMock uses the older expectation style whereas RhinoMocks and Moq both support the Arrange/Act/Assert approach where you specify you expected interactions as assertions at the end of the test like this:
stubStudentRepository.AssertWasCalled( x => x.Find(123));
Again, note that RhinoMocks uses a lambda instead of a string to identify the method. The ms fakes framework does not provide mocks at all. This means that in your stubbed out implementations (see the description of stubs above) you have to set variables that you later verify were set correctly. That would look something like this:
bool wasFindCalled = false;
IStudentRepository studentRepository = new DataAccess.Fakes.StubIStudentRepository()
{
DoesStudentExistInt32 = (studentId) =>
{
wasFindCalled = true;
return new Student();
}
};
classUnderTest.MethodUnderTest();
Assert.IsTrue(wasFindCalled);
I find this approach to be a little convoluted since you have to track the call up in the stub and then assert it later in the test. I find the NMock, and especially the RhinoMocks, examples to be more expressive.
Moles (Shims): To be frank, I do not like moles, because of their potential for misuse. One of the things I like so much about unit testing (and TDD in particular) is that testing your code helps you to understand where you have written poor code. This is because testing poorly written code is difficult. This is not true when using moles because moles are actually designed to allow you to test against dependencies that are not injected or to test private methods. They work similarly to stubs, except that you use a ShimsContext like this:
using (ShimsContext.Create())
{
System.Fakes.ShimDateTime.NowGet = () => { return new DateTime(fixedYear, 1, 1); };
}
My worry with shims is that people will start seeing them as "an easier way to unit test" because it doesn't force you to write code the way you should. For a more complete write-up on this concept see this post of mine:
https://jcoop.io/2012/05/21/solid-code-for-solid-reasons/
For more information on some concerns related to the fakes frameworks take a look at these posts:
https://jcoop.io/2012/03/16/38/
If you're interested in learning RhinoMocks here's a Pluralsight training video (full disclosure - I wrote this course and get paid royalties for views, but I think it applies to this discussion so I'm including it here):
http://www.pluralsight.com/training/Courses/TableOfContents/rhinomock-fundamentals
You are correct, but there's more to the story. The most important things to take away from this answer are:
Your architecture should make proper use of stubs and dependency injection, rather than relying on the crutch of Fakes and mocks
Fakes and mocks are useful for testing code you shouldn't or can't change, such as:
Legacy code that does not make use (or efficient use) of stubs
3rd party APIs
Resources for which you have no source code
Shims (known as "Moles", during development) is indeed a mocking framework that operates by way of detouring calls. Instead of painstakingly building a mock (yes, even using Moq is relatively painful!), shims simply use the production code object already in place. Shims simply re-route the call from the production target to the test delegate.
Stubs are generated from interfaces in the target project. The Stub object is just that -- an implementation of the interface. The benefit to using the Stub type is that you can quickly generate a stub without cluttering up your test project with many one-time use stubs, not to mention wasting time creating them. Of course, you should still create concrete stubs, for use across many tests.
Efficiently implementing Fakes (Shims, Mocks and Stub types) takes a little getting used to, but is well worth the effort. I have personally saved weeks of development time, through use of the Shims/Mole, Mocks, and Stub types. I hope you have as much fun with the technology as I have!
As I understand it, the Visual Studio team wanted to avoid competing with the various mock libraries available for .NET. MS often faces hard decisions like this. They are dammed if they don't provide certain functionality ("why doesn't MS provide us with a mock library; mocks are such a common requirement?") and damned if they do ("why is Microsoft acting so aggressively and driving its natural supporters out of the market?") Very often, but not always, they decide to hold back from simply providing their own alternative to available and well-received technologies. That seems to be the case here.
The shim feature of Fakes is really, really useful. Sure, there are dangers. It takes some discipline to ensure you only use this where necessary. However, it fills a big gap. My main complaint is that it is only delivered with the Ultimate edition of VS 2012 and therefore will only be available to a subsection of the .NET development community. What a pity.
Fakes includes two different kinds of "fake" object. The first, called a "stub", is essentially an auto-generated dummy whose default behaviour can (and usually would) be overridden to make it a more interesting mock. It does, however, lack some of the features that most of the currently available mocking frameworks offer. For example, if you want to check that a method on a stub instance was invoked, you would need to add the logic for this yourself. Basically, if you're authoring your own mocks manually now, stubs would probably seem like an improvement. However, if you're already using a more full-featured mocking framework, you might feel like there are some important pieces missing from Fakes stubs.
The other category of object offered by Fakes, called a "shim", exposes a mechanism for replacing behaviour of dependencies that have not been (or cannot be) decoupled adequately for standard replacement via mocks. AFAIK, TypeMock is the only one of the major mocking frameworks that currently offers this sort of functionality.
BTW, if you have tried out Moles before, Fakes is essentially the same thing, finally making its way out of Microsoft Research and into an actual product.
Regarding Fake (Shim + Stub) objects, it has been well defined above, though I guess the last paragraph in the last comment summarizes the whole situation pretty well.
Though a lot of people will argue that Fake (Shim + Stub) objects are good assets to have in some unit testing cases, the downside is that no matter if you're using Visual Studio 2012 or Visual Studio 2013, these options are ONLY available with Premium or Ultimate versions. IOW, this means that you WILL NOT be to run ANY of those Fakes (Shim + Stub) on any Pro version.
You may probably see the Fakes (Shim + Stub) menu option on Pro versions, but beware, there are some pretty strong chances that you will end up with absolutely nothing... It won't generate any compilation error telling you that something important is missing, options are just not there, so don't waste your time...
It's an important factor to consider in a dev team, especially if one is the only one using Ultimate version while everybody else uses Pro version... Moq on the other hand can easily be installed through Nuget no matter which Visual Studio version you use. I had no problem using Moq, the key with any tool is to know what they're used for and how to use them properly ;)

Syntax Comparison between Moq and Rhino mocks

My company is trying to decide if we are going to standardize on Moq, Rhino Mocks or MS Moles and Stubs.
I know Rhino Mocks and Moles and Stubs fairly well. But I am unfamiliar with Moq. How does the syntax work? Does it support Arrange Act Assert (AAA) like Rhino Mocks (I hear they created it, but I am not sure). Does it have strong typing?
Basically, I am leaning towards Rhino Mocks (using Moles where needed). But I don't want to do that just because I am familiar with Rhino Mocks. If Moq is in fact better or (even more important) easier to use, then I want to learn it and pick that one.
So, any one out there that has used both and feels like giving me a syntax comparison?
I've done a multi-part blog series on the differences between a number of mocking frameworks. Feel free to check it out at http://www.richard-banks.org/2010/07/mocking-comparison-part-1-basics.html
Have you looked at http://code.google.com/p/moq/wiki/QuickStart ?
Moq supports AAA and strong typing (via use of lambdas)
This project compares many mock framework against each other: mocking frameworks compare

What is wrong with Stubs for unit testing?

I just watched this funny YouTube Video about unit testing (it's Hitler with fake subtitles chewing out his team for not doing good unit tests--skip it if you're humor impaired) where stubs get roundly criticized. But I don't understand what wrong with stubs.
I haven't started using a mocking framework and I haven't started feeling the pain from not using one.
Am I in for a world a hurt sometime down the line, having chosen handwritten stubs and fakes instead of mocks (like Rhinomock etc)? (using Fowler's taxonomy)
What are the considerations for picking between a mock and handwritten stub?
There is nothing wrong with stubs, there is room for stubs, mocks... and spies. All are "test doubles", but with different purposes as explained in Mocks and Stubs aren't Spies:
[...] Before moving on, I'd like to
clarify and define some terms in use
here, which I originally discovered in
Gerard Meszaros' xUnit Patterns
book.
A Dummy Object is a placeholder object passed to the system under test
but never used.
A Test Stub provides the system under test with indirect input
A Test Spy provides a way to verify that the system under test performed
the correct indirect output
A Mock Object provides the system under test with both indirect input
and a way to verify indirect output
[...] And you can let this handy chart
guide your decisions:
PS: Mockito - The New Mock Framework on the Block is worth the read too.
I use the following terminology (introduced by Roy Osherove, the author of the Art of Unit-Testing):
A fake is called a stub if you tell it to fake something in case a method is called with such and such parameters. But if you also verify that such call actually took place or took place exactly N times, then such fake is called a mock. In short. a fake is a stub unless you call Verify() on it and then it's a mock.
Obviously, you will need to use stubs in some cases and mocks in others. So, criticizing stubs roundly is probably wrong and using stubs exclusively is probably wrong as well.
If you haven't started using a mocking framework (alternative term: isolation framework), you should keep an eye on them and reevaluate your options frequently. I went from manual mocks to NMock2 to Moq very quickly. Here's an interesting poll of programmers that shows what they use. Manual mocks/stubs are in the minority, but aren't that uncommon.
Mocks are just a lot easier to throw in. They are a real instance of your class, pre-stubbed with the ability to override the action of any method with minimal boilerplate.
There are lots of little considerations such as: If you don't want to deal with any of the methods, you can either have it act as a no-op or fail the test--your choice--but either way virtually no code.
How much boilerplate do you get when you stub out a class? How do you handle it if your class is final? Do you play tricks to get your stub on the classpath first, or do you use different source?
I recommend just starting with the mocks--It's easier all around.
There is nothing wrong with using stubs instead of mocks.
If you want to get technical, mocks are "smart" objects with expectations that can be verified. Stubs are dummy objects that return preset values. See Mocks Aren't Stubs.
But many people (myself included) prefer to do state testing with stubs rather than behavior testing with mocks. You inject a stub into the class under test, you call a method, then you check the state of the class under test. It tends to make for less brittle tests than asserting that the class's internals called method X of a mock object with argument Y.
I don't think you're in for a world of hurt. If you haven't started feeling the pain, you probably don't need an isolation/mocking framework yet. When and if you do, having handwritten stubs/fakes around isn't going to hurt anything.
If you have a lot of interfaces, or if your interfaces have a lot of methods, an isolation/mocking framework can save a lot of time over hand-coding stubs.
I like Moq a lot; I find it easier to use than Rhino Mocks for creating stubs.
Mocks and stubs is used to achieve a real unit test. You just mock all the dependencies, and unit test your class in isolation.
I'm currently using MOQ for mocking and stubbing.

An overview of unit testing terminology ( stub vs mock , integration vs. interaction )?

I'm using more unit tests in my projects and reading all the information I can online and am getting confused by a lot of the terminology. As a result I'm probably using these terms incorrectly in conversation and google searches.
Can somebody outline all the unit testing terms like the "fake" types as well as types of test ( interaction vs. integration )?
When it comes to mocks vs. fakes vs. stubs, there are actually a few different ways that people interpret them. I usually borrow the meanings defined by Martin Fowler:
Stub objects provide a valid response, but it's static -- no matter what input you pass in, you'll always get the same response.
Fake objects act like the real object, but they go about it in a simpler way -- such as a DAO that uses a Map to store data instead of a real database.
Mock objects are used in mock test cases -- they validate that certain methods are called on those objects.
Interaction testing is a general term that refers to unit tests which ensure that the interaction between objects is correct (making sure that expected methods are called). This is opposed to state (or classical) testing, which doesn't care what happens in the methods, so long as the resulting state is correct. These types of testing are compared in Fowler's article that I linked above.
Integration testing really isn't an aspect of unit testing, it is a level above the unit tests. It takes different units and verifies that they work together correctly.
This article from MSN Magazine explains the terms and goes into some detail with examples and some source code.
Basically these are the test doubles:
Dummy - Dummies contain no implementation
Stub - stubs are minimal implementations of interfaces or base classes
Spy - a spy will record which members were invoked
Fake - more complex, a fake may resemble a production implementation
Mock - A mock is usually dynamically created by a mock library and depending on its configuration, a mock can behave like a dummy, a stub, or a spy
Fowler did of course a great work at differentiating Mocks and Stubs but, to me, the XUnit Test Patterns book is the reference and I'd suggest to check Mocks, Fakes, Stubs and Dummies for a comprehensive comparison.
Yeah, I know, this is confusing and that's why I'd suggest checking Mocks and Stubs aren't Spies, then let’s spy and finally Mockito - The New Mock Framework on the Block too.
Regarding the different types of tests, a simplified explanation could be (this is not an exhaustive list):
unit testing: testing a single "unit", a method, in isolation
integration testing: testing the integration of several units (methods, classes, components, layers)
functional testing: testing an end-to-end scenario (from a user perspective)
All these types are useful and not exclusive, they actually just don't have the same intent.
I've read (and heartily recommend) The Art of Unit Testing by Roy Osherove. He uses a simplified set of terminology.
To paraphrase his book ...
Integration Test - any test that reaches outside of the current process or object to interact with something else
Interaction Test - a test on the way that objects work together
State Test - a test on the results produced by an operation
Fake - any stand-in object that's used instead of the real thing
Stub - a stand-in object that provides a dependency required by the code under test
Mock - a stand-in used to check the results of the test
Note that here both Stubs and Mocks can be provided by a Mocking framework - the distiction is as much about how they're used as the technology used.
this is an excellent book: http://xunitpatterns.com/
see: http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html
and http://xunitpatterns.com/XUnit%20Terminology%20Crossreference.html