background preloader

Mocks Aren't Stubs

Mocks Aren't Stubs
The term 'Mock Objects' has become a popular one to describe special case objects that mimic real objects for testing. Most language environments now have frameworks that make it easy to create mock objects. What's often not realized, however, is that mock objects are but one form of special case test object, one that enables a different style of testing. In this article I'll explain how mock objects work, how they encourage testing based on behavior verification, and how the community around them uses them to develop a different style of testing. I first came across the term "mock object" a few years ago in the Extreme Programming (XP) community. But as often as not I see mock objects described poorly. This difference is actually two separate differences. Regular Tests I'll begin by illustrating the two styles with a simple example. These two behaviors imply a couple of tests, these look like pretty conventional JUnit tests. Tests with Mock Objects Using EasyMock class OrderStateTester... Related:  Agile

TDD : Introduction to Moq In this post, I provide an introduction to Moq which is the newest of the Mock Object Frameworks. Moq is promoted by its creators as easier to learn and use than other Mock Object Frameworks such as Rhino Mocks and TypeMock Isolator. Moq takes advantage of recent VB.NET and C# language features such as lambdas and generics. When creating mock objects with Moq, you use lambda expressions to represent the methods and properties that you want to mock. According to the authors of Moq, you can pronounce “Moq” either like “Mock-You” or like “Mock”. Moq is actively maintained by Daniel Cazzulino. This post is about Moq version 2.5. Some Background, Some Philosophy, and Some Controversy There is just something about Mock frameworks that generate controversy. Some people have criticized Typemock Isolator for being too powerful. In this paper, Fowler makes several distinctions.

Master-Slave Pattern The Master-Slave pattern is often used for multi-threaded applications in which many instances of the same problem must be solved. (Travelling Salesman Problem, for example.) The master creates and launches slaves to solve these instances in "parallel". When all of the slaves have finished, the master harvests the results. Master-Slave pattern is also used for user interfaces and servers. In both cases the master listens for commands coming either from the user or from clients. In this example we have refined the Master-Slave pattern with the Factory pattern. Rhino Mocks « Niraj Bhatt – Architect&#039;s Blog I am no mockist. But I had to upgrade myself on this for one of my clients. Below are the few links I found useful. Hope they will help you as well. You can download Rhino Mocks here. Classic article by martin fowler MocksVsStubs is an essential read as well one on Dependency Injection which is critical in order to leverage on Rhino Mocks. I have slightly altered the code of Stephen Walter to take it a bit closer to real world (Though I only hope so :) ). public interface IProduct { string Name { get; set; } int Price { get; set; } } public interface IProductRepository { List<IProduct> GetProducts(); // Get the products from database } You don’t have the concrete implementations of either & you have been asked to implement a class called ProductManager which decides on whether a product is eligible for discounts. Now let’s say you want to test the above code. IProduct product = MockRepository.GenerateStub<IProduct>(); // Create a stub product.Name = “TV”; product.Price = 12000;

Mocks & Stubs : Leurres des Tests « Choses à faire Ces dernières années, les tests unitaires se sont imposés comme une technique obligatoire pour assurer la qualité d’un projet de développement. Pour simplifier le travail, de nombreux frameworks ont fait leur apparition pour à peu près chaque technologie. Cependant, certains comportements d’une application sont difficiles à tester par ce biais … Voici un « Mockingbird » ! Voici une liste des cas où un framework standard (de type xUnit) n’est pas forcément approprié : Les tests portent sur des parties du programme très dépendantes des données Imagineons deux comportements à tester, chacun modifiant des données sémantiquement proches. Plusieurs solutions sont apparues au fil du temps. Les « Dummy objects » Des objets factices sont passés à l’appel du comportement. Les « Stubs » ( ! Implémenter un Stub signifie remplacer un objet réel dont le système dépend par un nouveau point de contrôle, dont l’objectif est d’attendre des données très précises pour renvoyer une réponse connue. Et son Fake :

State Testing vs Interaction Testing Highly recommended reading: Fowler’s article Mocks aren’t Stubs. It’s a very clear characterization of the types of so-called Test Doubles (mocks, fakes, stubs, etc.) you can use to aid your unit testing needs, but also of the kinds of TDD you can do: classic (or state) TDD and mockist (or interaction) TDD. I got the feeling that the article seemed a bit biased towards mockist TDD, only to see in the “So should I be a classicist or a mockist?” section that Fowler himself is a classic TDDer ). I’m a state testing guy myself, but I always found it very annoying having to create all those little “mocks” to help me test classes that had dependencies. At first it felt very good not to have to create mocks manually, but very soon I started to feel the smell in all those lengthy setups where we were basically duplicating in mock expectations the entire interaction between collaborating classes which were completely unrelated to the object under test. .

Introducing BDD « DanNorth.net History: This article first appeared in Better Software magazine in March 2006. It has been translated into Japanese by Yukei Wachi, Korean by HongJoo Lee, Italian by Arialdo Martini and French by Philippe Poumaroux and most recently into Spanish by Oscar Zárate, Turkish by Selim Öber and Russian. I had a problem. While using and teaching agile practices like test-driven development (TDD) on projects in different environments, I kept coming across the same confusion and misunderstandings. The deeper I got into TDD, the more I felt that my own journey had been less of a wax-on, wax-off process of gradual mastery than a series of blind alleys. My response is behaviour-driven development (BDD). Test method names should be sentences My first “Aha!” renders something like this: The word “test” is stripped from both the class name and the method names, and the camel-case method name is converted into regular text. A simple sentence template keeps test methods focused I had introduced a bug.

Inversion of Control Containers and the Dependency Injection pattern In the Java community there's been a rush of lightweight containers that help to assemble components from different projects into a cohesive application. Underlying these containers is a common pattern to how they perform the wiring, a concept they refer under the very generic name of "Inversion of Control". In this article I dig into how this pattern works, under the more specific name of "Dependency Injection", and contrast it with the Service Locator alternative. The choice between them is less important than the principle of separating configuration from use. One of the entertaining things about the enterprise Java world is the huge amount of activity in building alternatives to the mainstream J2EE technologies, much of it happening in open source. Underlying these containers are a number of interesting design principles, things that go beyond both these specific containers and indeed the Java platform. Components and Services A Naive Example class MovieLister... Inversion of Control

New Version Of Rhino Mocks A dynamic mock object framework for the .Net platform. It's purpose is to ease testing by allowing the developer to create mock implementations of custom objects and verify the interactions using unit testing. Rhino.Mocks is an attempt to create easier way to build and use mock objects and allow better refactoring support from the current tools. It's a hybrid approach between the pure Record/Replay of EasyMock.Net's model and NMock's expectation based model. Rhino.Mocks originated from EasyMock.Net and attempt to improve on their model to create easy to use and power mocking framework. I created Rhino.Mocks because I wanted better support from refactoring tools such as ReSharper and because I don't like the way NMock handle parameterized methods (you need to pass fake constraints to get it to recognize the correct method) and the lack of extensibility [I required hacks to get to the result that I wanted]. Licensing: Rhino Mocks is Free Software which is released under the BSD license.

Applications et bases de données, comment tester ? « Choses à faire Même si l’on préfèrerait l’éviter, les tests unitaires d’une application web par exemple, portent souvent sur des parties du programme accédant à une base de données. Bien qu’il existe plusieurs outils servant à simplifier la tâche, voici tout d’abord des bonnes pratiques que je conseillerais à tout développeur. Bien séparer les couches Même si cela peut paraître idiot de le répéter encore une fois, il est indubitable que moins votre code concernera les accès à la base, moins il y aura de tests à faire en ce sens. Ainsi, concentrez ces parties par exemple dans des DAO, très loin des partie « IHM » et « Business » de votre application. Utilisez une base de données embarquée Je ne sais pas si c’est réellement une bonne pratique, mais il me semble idéal pour l’indépendance des tests qu’ils puissent être lancés n’importe où / n’importe quand, même quand le SGBD réel n’est pas actif. Évitez au maximum les dépendances Analysez ces deux classes et imaginez la plus pratique à tester : DbUnit (Java)

Visual Studio 2010: Test Driven Development Description Visual Studio 2010 brings with it several enhancements to help cut development friction and enable the developer to focus on the task at hand: writing high-quality code. In the following exercises we'll highlight several of the new features that the TDD developer can use to enhance his/her development cadence. Overview Test Driven Development (TDD), also frequently referred to as Test Driven Design, is a development methodology where developers create software by first writing a unit test, then writing the actual system code to make the unit test pass. TDD follows a cadence of “Red, Green, Refactor.” Note: This lab is not meant to teach you how to work with TDD; instead, it is intended to highlight Visual Studio 2010’s support for working in TDD. Test Driven Development in Microsoft .NET by James Newkirk and Alexei Voronstov, ISBN 0735619484 Pragmatic Unit Testing in C# with NUnit, 2nd Edition by Andy Hunt, Dave Thomas, and Matt Hargett, ISBN 0977616673 Objectives Setup Exercises

Adapting to Inversion of Control and Dependency Injection You might have come across the phrases IoC, Dependency Injection, Mocking among others, these are commonly used when talking about “Inversion Of Control” which is the full meaning of the abbreviation IoC. So what is this “IoC” that everyone is talking about? Inversion of control is a principle in Software Engineering, let’s just take a look at the Wikipedia definition of this In practice, Inversion of Control is a style of software construction where reusable generic code controls the execution of problem-specific code. Rather than explaining the text below, let me show an example of an application that does not follow this principle, but will when we’re done here! This solution simulates an order process, where we’ve got a window where we can place some kind of order and then we’ve got some sort of payment provider that executes the order request. The order form is very simple and looks like this: When we press the button this is what’s going to happen: Take a look at this line of code:

Patterns - Service Locator Oracle Technology Network > Java Software Downloads View All Downloads Top Downloads New Downloads What's New Java in the Cloud: Rapidly develop and deploy Java business applications in the cloud. Essential Links Developer Spotlight Java EE—the Most Lightweight Enterprise Framework? Blogs Technologies Contact Us About Oracle Cloud Events Top Actions News Key Topics Oracle Integrated Cloud Applications & Platform Services

Related:  Mock ObjectsMock ObjectsJava