RSS
Facebook
Twitter

Thursday, February 25, 2010

Getting started with Fake Objects – Part 2: How to create a fake object

In the previous post I’ve explained (briefly) what are fake objects and why they should be used – if you haven’t read it yet – I suggest you do so now.

In  a nutshell fake objects are used to break dependencies in unit tests to make the test faster, predictable and enable you to test the un-testable.

In this post I will show code! in fact we’re going to use isolation (Mocking) frameworks to create our very first fake object. I apologize in advance for using C# for my examples – just keep in mind that the ideas thought in these posts will also work if you use other programming languages and other isolation frameworks.

Let’s pretend that we want to unit the following code:

Note that I call another class in order to access my “database”, UserRepository, and obviously I haven’t got a database just yet – we’ll get to that in a minuet.

Simple – isn’t it? We have a pretended user service that help us manage users in our make belief site. Now let’s say I need to test the AddNewUser method. As you can tell from the code above I want to test two scenarios:

  1. If the user already exist –-> throw an exception
  2. If the user doesn’t exist (and all other validations pass) –> save the user

Test 1 – If user exist throw an exception

First I’d like to write a test that would verify what I secretly know – that my code works. The test would probably look something along these lines:

The test is simple enough I call the method expecting a specific exception to be thrown. If you are not familiar with the Throws method on lines 15-16 don’t worry – I wrote about it in a previous post.

The good news is that running the test causes an exception to be thrown, the bad news is that it’s a different exception from what I expected – The UserRepository class has not been properly configured (in my case not event implemented). In fact because that class (probably) calls a database I would not want to actually call it in my test. Doing so would require that I create a database and initialize it prior to running my tests and it’s not really what I need to test here.

Ideally I would like to fake the data access layer to return the needed result – in this test I just want it to return true whenever it was asked if a user already exists.

Luckily for us that’s exactly what Isolation (mocking) framework do. In .NET there is an option to use either Moq, RhinoMocks or Isolator, there are other isolation framework out for .NET but these are the top three.

I’m going to show how to create a fake object and set its behavior using Moq and Isolator – I leave it up to you to check and see how RhinoMocks does it.

Create fake object using Moq

Moq create a fake object using inheritance, it will subclass the object we want to fake and change the implementation of the methods according to our specifications, so in order for it to work we need Repository.UserExist to be a virtual method.

 

Note: Moq uses inheritance to create the fake object – so make sure that the method’s you’re faking are virtual and that the faked class is not sealed.

The test code has changed a bit – this is how it looks now:

  • Create a new Mock of the type we want to fake (line 4)
  • Set the fake object behavior, in our case when UserExist will be called – return true (line 5)
  • We get the fake object from the Mock (line 7)
  • What’s this – a new c’tor? (line 8)

If you’ve been paying attention you couldn’t have missed that I’ve added a new c’tor to our UserService class. The reason I did this is to enable passing the fake object to the production code. In fact the new c’tor is pretty straight forward – I replace the created repository with this “fake repository”:

This act of making the code easier to fake is referred as “design for testability” or “refactor for testability”.

And so with a new dll and a few minor code changed our test now passes – that it it throws an exception.

Create Fake object using Typemock Isolator

Typemock Isolator is a bit different from other isolation frameworks – it doesn’t use inheritance to create fake objects instead it uses the .NET profiler API to intercept low level method calls and replace them with fake code. This enable Isolator to fake about any method there is out there not just virtual methods along with other goodies.  The other difference is that it costs money and if you haven’t had a good look at my blog – I work there.

The main benefit of using Isolator you do not need to change your production code in order for it to work:

Just like in Moq we create a fake instance of UserRepository (line 4), set its behavior (line 5) but unlike Moq we can tell Isolator to replace the next instance created of a certain type with our fake object (line 7).

In face using Isolator I do not need the faked object methods to be virtual – it just work.

The result is the same – the test passes.

 

In the next part I’m going to explain about another important feature of Isolation frameworks – stay tuned…




Sunday, February 21, 2010

Survival Skills for Developers

I’ve talked about this post during the recording of the latest This Week In Testing episode (soon to be available). It is well written post by the blog owner - Derek Hatchar that explains his take of the skill a developer need to have in order to survive in this highly competitive work – read it here.

I feel that I didn’t give enough credit during the webcast to the post – this is a good list and I guess that every software developer (or manager) has a similar list that he (or she) thinks are essential in order to “stay relevant”.

What I did not like in the list is the fact that it seemed to be mostly (but not only) technology based – I don’t think that every developer out there must know how to print or send email with his language of choice.

During the webcast Doron has asked me about my list of development skills needed and it took me more time to answer then it should have, it should have been an easy task – name the skills make one developer better at his work then others – I’ve though of the subject quite a bit and the list below is my take on the survival skills for developers:

  • Basic operating system knowledge
    It pains me to meet developers that have no idea how memory is managed, what are threads and that file is just a bunch of bytes. I don’t think that you need to compile your OS kernel daily nor do I think that every developer should use Linux, Solaris and Windows - but you do need to know the basics.
    Although OS understanding seems pretty theoretical subject I cannot start to count the times this knowledge had helped me write better code, solve a task or find a bug.
  • Programming languages
    I said it before and I say it again this is the main tool of our trade and the more tools you have the better you can do your job. You don’t want to be the guy that only knows C# and cannot read the VB.NET examples or that fellow who only solves problems in Java even if the rest of the system was written in C++. But there is much more to learning programming languages then adding another line to your C.V. with each programming language you learn and use you acquire insight to how to do things in another way. If you’ve been using OO language since graduation – try learning functional or dynamic programming by learning a new languages and see what happens.
  • Communication skills
    Unless you’re the owner and sole employee of your company as well as it’s owner you need to interact with other people to get the job done. Explaining your view and ideas is important. Most positions you’ll fill will require the ability  to influence others without authority – from software developer to architect or a contractor we all need  to be able to communicate our ideas and not less important listen to others.
  • Know your tools
    That where I think scripting languages, unit testing, XML, HTML and some of the points from Derek’s post come in. Whatever you do you need to be in control in whatever you need to get the job done – efficiently.
  • Learn, Learn and learn
    There is no simple truth in the business of software development, the only constant is that it keeps on changing all of the time. You must have the curiosity and the will to keep learning to stay in the race. You can always settle for a well used technology and keep using it as long as possible but sooner or later something new will come and you’ll become obsolete. Knowing how to learn is much more important – or as my co-host said during the webcast - I don’t know how to print documents but I guess I can find out quickly if I ever need to. 

Juggling metaphor by backpackphotography.

That’s my list of essential skills – what is yours?




Tuesday, February 16, 2010

Best multi threaded programming tool ever!

If you’ve been developing software for a few years you might have noticed an increase in the need of parallel programming and it’s no wonder in these day and time when most computers have at least 2 cores that can run two actions at the same time.

Along with the need comes the solution - tools and languages that would make parallel programming easier – because “it’s way too hard to understand multi-threaded code” .fast cars by myfear.

Right now I can see two distinct groups of products that aim in making our job (development) easier:

  1. Programming languages
  2. Error discovery tools

The first group try to solve a fundamental problem with the way a programmer write code in C++/C#/Java or whatever language you’re currently using. Instead why not use a language that has been able to completely (or mostly) eliminate deadlocks and race conditions – either by using message passing for interaction between objects(Erlang, Axum) or by having immutable objects (F#).

The second group combines of (amazing) tools that by using statistics or plain brute force discover if your code has multi threaded problems (again race conditions and deadlocks).

 

Have we gotten to multi-threading heaven or are we just lacking the right tool that will make development not quite so hard.

 

I believe that in the upcoming years we will see some more tools and languages aimed at helping us write better multi threaded code faster, I do believe that no tool will free us from understanding what our software actually does. Just like the fact that we still need to know a bit of logic to write the simplest application (other then Hell-o-world) we will forever need to understand how our code behaves when run on several processors at the same time.

warp #1: My fast Colt by bass_nroll.

I believe that multi-threading application development does not need to wait for the right tool just for the right developer.




Wednesday, February 10, 2010

Getting started with Fake Objects – Part 1: why fake is better then mock

If you’ve been writing unit tests for a short while you might have noticed that writing good unit tests is hard. The object under test can be hard to create because it require dependencies that you just cannot provide or some complicated environment is needed just to make the test pass.

When writing a unit test one of the challenges is how to code around the dependencies of the object of his test. In other words – how to isolate the code under test from external dependencies.

Fake, Stubs and Mocks

There is a difference – at least for some people - between mocks, stubs and fakes. for the purpose of this post and every unit test you will ever write – it does not really matters.

Some mocking framework have the distinction between these types of objects and for the sake of terminology (which some people seem to like) I’ll explain the difference between the two:

  • Stubs are used to replace an object that your object depends on
  • Mocks are used to verify that happened to that object (while faking some, all or none of it’s calls)

In a nutshell you do not care what happens to the stub during the test, but you do want to know something about the interaction between objects when you’re using a mock.

For a short (and good) explanation of mocks take a look at Roy Osherove’s mock objects elevator speech.

I prefer to simply call them “fakes”, because unless the tool I’m using forces me to differentiate between them – I don’t really care what they are as long as I write a good unit test.

When to use Fake objects

If you need to simulate the behavior of a complex or hard to create object – use fake object.

There are other good reasons for faking an object:

  • Make the test deterministic – unit tests should have the same result each time you run them. If your object returns a non deterministic value that would change each time you run the test, by faking that class behavior you can make it return the same value each and every time.
  • Hard to set up environment – if you need a database (with specific data), a server or similar components for the test to pass.
  • When objects do not yet exist – during development you cannot rely on all of the objects you need to be when you need them. You might need another class that was not written yet or some algorithm that was not implemented yet.
  • Difficult to reproduce state – e.c. you need to check what happens when your client receives a network error while calling its server.

Fake objects are used to isolate your code from external dependencies. You can write your own (called hand rolled mocks/fakes) but there is no reason to reinvent the wheel – there are isolation frameworks for most mainstream languages – check Wikipedia’s list of mock object frameworks for your language of choice.

What Isolation framework can do for you?

All isolation (Mocking) frameworks I came across do the following three:

  1. Create fake objects
  2. Set fake object’s behavior
  3. Verify method was/wasn’t called

Some frameworks have additional capabilities – depending on the programming language their internal operation (how they work).

 

In the following posts I will explain about each of the three above – along with code examples!




Friday, February 05, 2010

Links: Being Successful with Agile and unit testing

It is always nice to hear when a fellow developer succeeds and what makes these posts even better is the fact that they also contain valuable tips as well.

Lessons learned from an Agile project (David Tchepak):

Dave^2 writes about an agile project he’s been part of for the last 18 months - and he has a lot to tell you about it. They’ve been doing XP and Scrum using 2 week iterations and as far as the post goes it was great.If I have seen farther than others, it is because I was standing on the shoulders of giants by Lady AnnDerground.

The post explains about several points that attributed to the project success:

  • Short user stories
  • Momentum
  • Feedback
  • Acceptance testing
  • Do what works
  • End-to-End as fat as possible

But don’t take my word for it – read about it in his blog.

Six Months Down The Line – Unit Testing (Isaac Abraham)

Isaac project is getting close to its first release and after six months of practicing TDD (Test Driven Development) – he has some insights on unit testing and how to make them work for you.

This is the first project he’s been using TDD and unit testing all the way and as far as I can tell from the post it went great -no trivial task.

He has a few tips on how to succeed with unit testing such as “keep your test as granular as possible” and “keep your compile time down”.

The post has a nice overview of the tools used (MSTest, Rhino-Mocks) along with Isaac’s experience with them.

All in all a good post to read if you’re interested in reading the lessons learnt from a successful TDD first timer.

Thursday, February 04, 2010

How to collect NUnit test results in TeamCity

I’ve been using TeamCity for some time now and I love it - It’s easy to install and use. TeamCity can also run unit tests using several test frameworks and collects data about the tests runs as long as you’re using one of the supported build scripts (e.c. NAnt or MSBuild) – from how many tests have been run to a list of problematic unit tests that tend to fail.

All of this is nice and dandy but what if you happen to use a different build script tool – one that doesn’t have TeamCity integration?

At Typemock we use FinalBuilder to create our build scripts – we run it using TeamCity “Command Line” runner by calling an executable that runs the script. The problem with this method is that TeamCity does not collect the test run information automatically – or does it?

On a closer look at the runner tab on the build configuration you’ll find this:

image

That’s right – TeamCity can load data from the last run – and it has support for NUnit xml report.

All is left is to configure NUnit to output the test result at the end of the run – Simple.

 image

Tip #2

If you need to write messages from FinalBuilder just add the following JavaScript command: Action.SendLogMessage("Hello World!",stInformation)found via StackOverflow

 

Happy coding




Related Posts Plugin for WordPress, Blogger...