Showing posts with label tdd. Show all posts
Showing posts with label tdd. Show all posts

Friday, August 7, 2009

Ensure test coverage when refactoring to mocks

Using real dependencies in your tests will lead to pain. A lot of pain.

Most likely, your test fixtures lack coverage, test the wrong class, be difficult to read and don't do what they say.

Eventually, your team will decide to abandon testing or introduce mocking/stubbing.

Refactoring your existing tests will be a major endeavor.

It will be tedious and repetitive.

You will feel like you are wasting time.

You will have a strong urge to rush.

To help you out, I've outlined the steps needed to refactor a test to mocks. I've noted steps that are easy to skip (yet still important) with *

1. Make a copy of the TestFixture -- call it TestFixtureNameWithMocks -- this will ensure you do not lose test coverage and can commit often.

2. Comment out all tests

3. Delete the setup code

4. Take a moment to read the first test
  • Does this test actually test anything? (if not, figure out what it should be testing and get it working right in the original fixture first!)*
  • Does it verify state of the CUT?
  • Does it verify state of a dependent (or dependent of dependent of dependent...)?
  • Does it do more than one verification?
6. If there is more than one verification, determine how many tests you actually need.

7. If your test relied on the state of a dependent, verify that behavior is tested in the correct test fixture (i.e. the dependent's!). If not, you need one, use this test as an example. Create a failing test now, before you forget. If you have a rabbit hole of dependents, make a test for the top dependent.*

8. If needed, break out the test into multiple verifications -- select one to do, comment the rest.

9. Uncomment test and rewrite using mocks/stub. You will find that some tests are quite different. Some similar. Some will require refactoring of the CUT or dependents to make mock friendly.

10. Run the test and verify it passes. If it does not, figure out what preconditions are missing -- check the CUT and old test. Keep doing this till it passes.

10. Comment out code that is being tested.*

11. Run test, verify it fails for the right reason. If it does not, check the test and verify your assumptions. Make it fail for the right reason!*

12. Uncomment code, verify it passes. If you didn't change code in 11, you can skip this step -- I am paranoid and usually do it anyway :)

13. Repeat for every test in the fixture (and any new tests you find). Pull out common setup if needed. Rename tests since the original names will most likely need it :P

14. Remove old test fixture and rename new one.

If you made it this far imagine how long rewriting one test takes. In the best case you still need to run each test at least 2 times.

Now imagine doing this for more than one class.

How about for how many tests exist by the time our tests are painful enough to require this change.

If done right, this will take a lot of time. If we do it wrong, we take great risks and have tests that give us a false sense of security.

Clearly, if we want to continue delivering end user value, we cannot do this all at once.

Here is one way to do this:
1. Whenever a test is updated (bug fix, enhancement, refactor), update the test fixture to use mocks.
2. Have a policy where it is ok to have 2 fixtures for 1 CUT (one with mocks and one without) to encourage people to start using mocks w/o the overhead/context switch of a big refactor. Stress that finishing the refactor takes precedence over starting new work.
3. Let everyone on the team know that it is expected to take time and include that in commitments and estimations.
4. Remain disciplined

Good luck!!

Wednesday, December 3, 2008

The need for speed

I say this a lot, but I love TDD. Besides the list of reasons about how it improves code or simplifies solutions, TDD is fast.

TDD is fun because it goes so quickly. Write a test, make it pass, refactor, run more tests.

I love the flow. I love adding a new interface and using it without worry about implementation. I love knowing after I make a new test, something in the app is different and it works. I love living in the tests and only running the application before checking in.

However, the moment the tests slow, the practices start to slip...
  1. Writing code and verifying it works by launching the app, then creating the tests
  2. Making the test pass before verifying it failed.
  3. Not running all the tests before check in.
  4. Not refactoring because it takes too long
  5. It stops you from working close to 5 because you don't want to wait for the build
  6. Not adding tests at all because you don't want to break the build and don't want to wait to find out
  7. It ruins all the fun.
These things all lead to poor test coverage or tests that don't actually do what they say. Yeah, on paper your coverage may look nice, but there's plenty of code you can delete w/o breaking tests. Coverage makes sure a code path is followed, it does not verify the path was actually tested.

So, how do we keep our tests running quickly?
  1. Mocking. Reduces the amount of time spent creating dependencies and their dependencies and the rabbit hole of dependencies that nobody can even see.
  2. Use a one to one ratio of test assemblies to application assemblies -- don't waste time waiting for things to build that you're not testing.
  3. Keep interfaces and implementations in separate assemblies. Dependents should only be recompiled if the contract changes, not the implementation. This allows you to complete the usage of a change, without worrying about the implementation. Sure, you can just resharper, but are you really going to add tests for a new method right now?? If you do, you break the rhythm, if you don't, you have to remember, somehow, that there is code that needs to be implemented somewhere that your tests won't pick up... you'll start thinking about the implementation or just forget and break the app without anyone knowing.
  4. Simplify. Keep tests short. Only create items in setup that are used in all tests. Avoid factories for creating concrete classes because they hide dependencies and make it too easy to use real implementations instead of mocks. Avoid repeating yourself in tests, don't assert the same thing twice, it doesn't help to have the same failure twice but it does slow everything down.
In general, follow the best practices of test writing! They're there for a reason. No point in experiencing the pain of the nice people who figured them out. Take advantage w/o having crappy tests, lots of pain and failure.

Friday, June 6, 2008

Followup to Testing with Mocks

Thanks to everyone who came to the Testing with Mocks TLC session at TechEd.

Here are some links of things we touched on during the class. Please leave a comment if I missed something :)

Test Smells:
TDD Anti Patterns -- Be sure to read the comments, there are some valuable smells there too!

Books:
The Art of Unit Testing
Working Effectively with Legacy Code
TDD by Example (Kent Beck's book)

Rhino Mocks:
Ayende (creator of rhino mocks)
Google Group
Reference Guide

Other .NET Testing Frameworks:
nMock
TypeMock
Moq

Test Runners:
nUnit
mbUnit

Tools:
Resharper
TeamCity
CruiseControl.NET
CruiseControl.rb

IoC Containers:
Castle MicroKernel/Windsor
Spring.Net
StructureMap

Community:
Alt.Net

Wednesday, October 24, 2007

Fairfield/Westchester code camp

I will be at presenting a session on Testing with Mocks at the the Westchester/Fairfield code camp on November 11.

Register here

The session is a shortened version of the tutorial Oksana and I are giving at the Agile Development Practices conference in December.

Hope to see you there!

Friday, September 28, 2007

Good practices are beyond testing

Before using TDD, I was a big fan of separation of concerns, single responsibility and inversion of control. These things have proven over and over again to be priceless.

When I started using TDD I loved is how it enforced these principles. I couldn't maintain or write tests without them. Testing even forced the need for dependency injection and inversion of control containers.

The tests started to validate and enforce important behaviors. Behaviors some people don't appreciate. Sometimes these had been a hard sell.

TDD became an easy justification for best practices. How awesome!

Enter mocking libraries that don't require DI. You can mock everything from constructors to static methods. Mocking methods on the CUT is as easy as creating a new class for that responsibility.

With this, its easier to make a large class and use static utils and real constructors. Now you can test without adding those pesky things that add to the confusion of object oriented code... you know stuff like interfaces, polymorphism, encapsulation...

If we don't need DI or interfaces for testing, then why do we need them? If testing can happen without it, then that behavior isn't driven, right? Why can't I make a big class if its testable?

But these design principles have been around for a long time and for good reason. DI, single responsibility and separation of concerns were not born from testing.

Tuesday, September 11, 2007

Too many mocks?

As I write tests, I use mocks to push off behavior that is difficult to test. This pattern helps me focus on the class under test and drives my design.

At what point can you push too far?

With TDD, its all about your tests, so anything that helps you write a test is the right thing to do. I am confident the tests drive a good design.

However, sometimes there are border cases. You may wonder if another class is excessive.

In this case ask a simple question: is this behavior the single responsibility of this class?

Usually the answer is no. The behavior I'm testing is combination of responsibilities and so, yeah, a mock is a good choice.

Sunday, June 17, 2007

A rose by any other name

Using English to describe a test is quite a challenge. It is demonstrated in the various styles present in the community. My naming conventions, much like my development style, change constantly.

When I first began TDD, my names looked something like this:
public void MethodATest()

Look familiar? What does this test? Well, it gives me a new method. It tells me I have to test all the functions of this method in one test. It does not give business value and does not give any clues when it fails.

This methodology did not last long -- my tests were too large, too complex and tested too many things. When I had a failing test, I had some idea what was wrong because I remembered the method, but my tests did not evolve with my code.

Eventually, my next naming convention looked a little more like this:
public void MethodADoesThis()
or
public void MethodADoesThisWithThat()
or
public void MethodADoesThisWithThatWhenThisIsTrue()
(sometimes this was: public void WhenThisIsTrueMethodADoesThisWithThat())

Although this naming was more descriptive, it was slightly ambiguious, drove too much design in a single test and was not easily read.

The anatomy of a test is basic, there is a setup of preconditions (context), execution of the code (call method), and then verification process (Assert or Verify).

What if our name told us what to put in each part. Would you know how to write it? Would you know what its testing?

Back in February, Aaron made a post about loosly coupled mocks. His naming convention is great. Its simple, has clear rules and forces you to think about what you are testing. It not only follows the anatomy of the test, but puts you in your test before you write it.

What it looks like:
public void Method_Context_Expectation()

So, for the simple hello world test:
public void GreetTheWorld_Always_CallsConsoleWriteLine

Always is a weird context right? Well, its true and writing it helps understand what you are designing.

Now, what if we want to add a condition to calling GreetTheWorld?

Say we only greet the world, if the world exists:
public void GreetTheWorld_WorldExists_CallsConsoleWriteLine
public void GreetTheWorld_WorldDoesNotExist_DoesNotCallConsoleWriteLine

This naming convention also helps us understand when to use SetupResult instead of expectations. In the methods above, we are using the world as context, and the console as verification so we would say SetupResult.For(theWorld.Exists) instead of expecting it -- we don't want our test to fail from context, only when our expectations are not met.

Another nice thing about this convention is detecting smells in my design. If I have 10 methods for GreetTheWorld, because there are many contexts or expectations, I'd know GreetTheWorld had too many responsibilities.

Who would have thought a simple naming convention could have helped so much, thanks Aaron -- or rather the unnamed person Aaron stole this from :P

Saturday, June 9, 2007

I taught my husband TDD today

(Scott left a comment that made me edit this post a bit)
In less time than it took me to write this post. Can you believe that?? He learned to drive design. He got it!

We started our lesson when I was writing another post about TDD (big surprise, right?). He said I should post some examples. I said that my examples wouldn't be useful without the reactions of the audience. Everyone learns differently.

He gave me a simple example to do, test drive a class that writes "Hello World" to the console. I started explaining what makes this simple problem not so easy to test and we decided to try out the example together.

Asking questions is a great tool to help someone learn, it makes the learner realize conclusions. Figuring out the right questions is always difficult and this morning was no different.

I asked lots of questions. They were focused on one thing: How can I make the introduction of a mock organic?

Eventually he suggested we put Console.Writeline in our CUT, then we refactor it to be testable.

This made me realize my questions were not right.

I needed to teach him how to think in the test. I knew this was a major key how I learned TDD, but I thought it was an evolution.

I was wrong.

In this moment, I realized that learning TDD isn't about writing tests. Its about leveraging polymorphism to verify responsibilities and interactions.

Once I realized this, I only needed to ask one question:
Is there a way we can put something between our CUT and the System.Console to verify the right method was called?

In a few minutes we had an IConsole and a MockConsole implementation. A few minutes later we had a working test, a minute after that we had a console application that wrote hello world.

During his implementation of MockConsole, he found many limitations. After we had a working application, we went back in the test and replaced MockConsole with a RhinoMock.

In the end, he understood how the test drove his design, why it did, why he used a mock and appreciated a mocking framework.

It was awesome.

I'll let his reflection on his learning speak for itself:
I really like TDD. The code you end up with is really good. Its the minimum amount of code to write to make your code testable. The difficulty between just programming and test drivent development is very different...

On the first day of college, you write hello world straight to the console without any understanding of coding, its the real basics.

On your first day of TDD it takes a few layers in between to do it right, its geometrically more complicated, but its only adding a some subtle difference, like IConsole. It gives you the round trip of object oriented programming with simple examples that really illustrate why you do the things you do with object oriented programming. It really takes a great understanding of OOD to appreciate TDD and do it right.

Deciding what tests to write and how you write them are hard, harder than writing the code.

Thank you, that was nice.

Thursday, May 31, 2007

But how could a test drive design??

Good question, I'm glad you asked...

Actually, I asked myself during my long a** commute, which gave me a lot of time to reflect.

The weird thing about TDD is that there is no design.

You don't design tests. You write them, one at a time.

This is something that makes TDD difficult. Even after I understood the basics, it was still a challenge to stay with it. I had to stop thinking about how to solve the problem and focus only on how to test the solution.

It's not that I don't think about designs at all, but I'll only design up until the point I know I'll be able to start my first test. This design is focused on high level interactions and the goals of my solution.

When the TDD light bulb went off above my head, my thinking changed to this:
What can I do to make this test as easy as possible to write?

Thats it. Kinda lame looking at it now, but really, thats it. When I focused on testing and that alone, that's all that remained.

If you have difficulty dispelling design noise, pretend you are Harry Potter and have your very own pensieve (that would be pretty cool, no?). Put the thoughts in the pensive. They will be there when you have the focus they deserve (In real life this works well with index cards)

Unless it is a new user story, I throw it out. I don't worry about it, because if I need it, it will happen.

But what if I forget? Are my user stories satisfied? Are my acceptance tests passing? I guess I don't need it.

But I need to refactor my code! Well, I should be doing this all the time! If I didn't have a chance for whatever reason, next time I am in the test, it will be so painful, I'll refactor. I trust myself and my team. When this happens a lot, I need to think about what done means (this is another topic)

How do I make tests easier to write?

When I can't make a test without getting frustrated or overwhelmed with what-ifs or setups, I introduce a mock and encapsulate the behavior. Using that mock just made my life a whole lot easier.

Did I just drive the creation of a new interface? Is there a new interaction that didn't exist because it was the easiest thing? Will my class be more simple because its not doing something too complicated? Will the new class be cohesive because it was created for a specific purpose?

Wow, not only am I creating a new design as I go, but all other things happen because I'm trying to make my life easier.

Anyone else see the beauty here?

Or the power?

When I have a very complicated problem, I break it up organically by test driving. Each part not only makes sense, but is easier to implement because I am able to focus on small pieces. I have instant gratification that each worked on its own, as it was created, without any integration.

Sweet bonus, the solution doesn't do anything extra and I didn't go on any tangents because I didn't want to write extra tests.

Extra sweet -- I spoke to coworkers, took a lunch break, wrote a blog post and had NO fear my momentum or focus would be lost.

Writing tests is more difficult than writing code, but when I focus on making my tests as easy as possible to write, it keeps me in the test, drives my design and simplifies my thinking.

Sunday, May 27, 2007

TDD, What a bitch

Whenever I talk to someone who is interested in learning TDD I let them know that it is a very difficult concept to put into practice. It takes a lot of discipline and significant changes in the way you think and code.

Nobody mentioned this to me before I started. Everyone spoke of TDD like magic -- it changes your design, its the best thing ever, its so simple, all you need to do is write your tests before your class, you'll love it... (Ignore the man behind the curtain!)

After a few days of trying, I began to think something was very wrong. I wasn't quite the developing genius I thought...

That couldn't be true!

Like any reasonable person in my situation -- overstressed, too many responsibilities, tight deadlines, stakeholders bothering you, etc... I continued to pound my head against what seemed to be a steel wall of TDD that just wouldn't fit.

My head (now bleeding and bruised) was focused on how to solve the problem instead of how to test the solution. I didn't know it at the time, but until I changed this behavior, I would always be fighting my instincts and not gaining the benefits.

Fast forward two months and I was still, well, sucking, but not as bad. I had some test coverage, I wrote some classes test first, but I did not test drive every class, it seemed like too much work. I also didn't understand mocks, at all, and gave up on writing my own mock classes after about a day, so no interaction testing and lots of coupling.

It was very frustrating to have 1/3 of my tests fail if I was working on a common entity or if a bug showed up. Also, because I was coupling all my classes together I wasn't seeing the full benefits of test driving.

My focus was just as bad as coding before. If I needed a new behavior, I'd have to code. This meant testing the other class, which may cascade into other tests. Thinking about it, I think my focus was worse. Sometimes I could write a stub for the new behavior, but say I was creating a method that returned a boolean that had different responses that I needed to test... And there is the setup to get it into each state. And thats just a boolean assuming there's no interactions...

My thinking was in the same place it was a few months earlier. The only difference was I could write a unit test before I wrote code. But I wasn't test driving design. I had the design in my head. I was writing the unit tests for the classes and interactions I already decided I needed.

Fast forward two months: New job, new project, fresh start, woo hoo!

With this project, I was determined to understand TDD. A lot of bright people that I respected were saying great stuff and I was going to get it.

My first step was to understand nMock.

I knew using real classes in my tests was killing my focus, but I didn't yet know how much it affected my design. I read the nMock web page, explaining the api, about 500 times... "Okay," I said to myself. "You can use an interface before its implemented and verify its been called."

It sounded so simple, it read so simple, yet it made NO sense to me.

My delight in using mocks (once I figured out how to use them) was focused on several things -- I could focus on the test I was writing, my tests weren't failing because of another class and my tests were a lot simpler because I didn't need to put in knowledge about other classes to verify or assert behavior in the CUT. Implementations of interfaces used in tests didn't affect the tests anymore.

After a few weeks of nMock, what I began to notice was that my design, code, thinking, and mind was changing.

A lot.

I only made a class after it was being used as an interface in another class. That class' only public methods were in that interface. I never debugged my application. I almost never debugged my tests. My test coverage was over 90%. My design evolved through the tests.

I was test driving. Finally!

Making tests was so focused and had immediate results I was addicted. At some point, something happened in my brain and this great thing called TDD finally came in. I didn't want to write in the CUT first, because it wasn't how I was thinking. It seemed like more work.

I was in the test.

Saturday, March 3, 2007

Failing at TDD

Someone asked for more clarification about how I failed at TDD... I gave reasons why I failed, but no measurement of success. In the class, I had said that I failed until I finally changed my way of thinking and actually got what test driving is all about...

But I was thinking about this statement on the way home and this isn't true. Even after I understood how to test, my classes under test would outgrow their test fixtures because I wasn't in the habit of writing tests first or the tests were too rigid to change or I just wanted to get something to work really quick without having to write a test... a little extra code here and there eventually leads to a lot of failing tests, ignored tests, ignored assemblies and then total failure...

A few years ago I was lucky enough to have lunch with Bob Martin and we had a long talk about discipline. I would argue that this is the most important attribute for test development (he really knew what he was talking about, how little I knew then).

I finally considered myself successful in TDD when I had several projects that were test driven, and continued to evolve test driven as well... i.e. I was finally successful when my tests were refactored with the rest of my code, my tests continued to drive change and it wasn't painful.

Hope you had fun at code camp



For everyone who sat in on our talks at code camp, thanks for being a great audience. I'll post some notes, answers to questions and code samples in the near future.

We hope you had fun and maybe learned a thing or two :)

Thursday, February 15, 2007

Code Camp 2007

Looks like I'll be giving 2 presentations at Code Camp 2007 in NYC with a fellow developer from Oxygen, Oksana Udovitska. We're hosting two talks, The Gentle Art of Pair Programming and Testing in C# with RhinoMocks. Hopefully, people will learn something or at least be entertained. I'm thinking a code session taught by two hot chicks will be enough! hahaha

Code camp is in midtown on March 3rd, which is a Saturday (yeah, totally sucks, no?) and its from 9 - 6 or something like that...

Luke Melia -- another excellent developer on our team is also hosting a chat about leveraging the WPF command pattern with dependency injection. It should be good!

base test class

one thing that can make your tests real messy, real fast is duplicated code. however, with mocks, its really hard to get rid of duplication and keep your code readable.

a simple first step to uniform tests is a base test class that you inherit from in all your classes. use this class to setup your mock repository, replay, verify, tear down and do any custom setup your application needs for all your tests.



[TestFixture]
public void BaseTest
{
protected MockRepository _mocks;


[SetUp]
public virtual void Setup()
{
_mocks = new MockRepository();
}

[TearDown]
public virtual void TearDown()
{
}

protected virtual void FinalizeAll()
{
_mocks.ReplayAll();
}

protected void CreateMock<T>()
{
return _mocks.CreateMock<T>();
}

protected T XamlSerializeAndDeserialize<T>(T original)
{
using (MemoryStream stream = new MemoryStream())
{
XamlWriter.Save(original, stream);
stream.Position = 0;
return (T)XamlReader.Load(stream);
}
}
}


We keep the MockRepository protected because there are so many methods on it that inheritors may want to use, but use the base tests methods usages of _mocks when they exist. Also, we call the method that ReplaysAll "FinalizeAll" because methods that override often do more than just replay the mocks, they finalize the state of the other objects in the test. However, this may not be the best name, considering what "finalize" means in the c# world...

If you use an object management framework, logging or other common mocks, the base class can take the responsibility of setting those up.

As you can see, we added a method, "XamlSerializeAndDeserialize," since we test this in many of our classes, you could put this in a separate Assert class too, but it really depends on how often its used and what your team likes.

As your tests evolve, factories to create common mock objects and classes to do custom Asserts are also really helpful. One test class we've found really helpful is a PropertyChangedEventTester that will hook into any class that implements INotifyPropertyChanged and keep track of events.

all about the mocks

i love mocks. i really do. if i could, i would marry mocks, have lots of mock babies, be a grandmock; you get the idea...

the top reasons i love mocks:
1. focus only on what you are testing
2. other classes won't break your tests
3. create new interfaces and use them before they exist
4. use functionality without knowledge
5. i hate math
6. keep the file system, networks and other real resources out of your unit tests

i'll post examples of each of these reasons

a lot of black box testers have valid reasons for disliking mocks, but the benefits surpass any downside i have ever read or encountered. i use rhino mocks, which uses reflection, so some major downsides of mocks, such as difficult refactoring and type casting are completely avoided.

did i mention i love mocks?

thank you rhino mocks!!!

One other must with mocks is dependency injection. In the past I've written my own object management framework to handle injection, but we've been using the castle framework and its totally excellent, i love this too!!! It takes away all the thinking of dependency injection and lets you focus only on your tests and interfaces. An absolute must!!

Wednesday, January 24, 2007

Lazy with untested code...

I'm a little backwards... I think most people who get into testing are paranoid about untested code, so they are more careful when they are in the realm of code untested. I on the other hand am so use to testing and so confident in the coverage that I almost never run an application after I make a simple change, just run the tests and go... So, when I happen to refactor something, like change a base class that had an inheriting class that wasn't under test, I've caused crashes and other bugs. Before testing, I was so disciplined in fine tuning my code -- no bugs, no problems -- perfect code (well close to it). Its kinda weird that with testing, my untested code has become so poor....

Testing makes writing the code more difficult cause well, personally I find testing to be a completely different way of thinking, but it makes life after the test is written so much easier. I don't have to worry about a refactor breaking something cause its all tested!

Anyway, the point is this:
1. I should be less lazy when I change things that aren't tested
2. Everything should be tested!
3. If I find something that falls under (1) I should enforce (2)

Anyone else have this problem? Has anyone found that pairing and testing made them a more lazy/less disciplined developer when they code alone and/or without testing?