Brendan Enrick

Daily Software Development

Time-Tested Testing Tips - Part 3

Context switching is very costly and this same issue can be seen when writing tests, but I would argue most importantly in maintaining and reading tests.

There are three main parts to a test. The first part sets everything up, the second part takes some action, and the third part expects certain results given the the start and the action taken. In this tip I'll be talking about the first part, the setup.

Keep Test-Relevant Details Visible

I've said in the past to treat test code just like any other code. However, there are a few reasons to break from this rule. One is the context switching which will be caused by extracting information which is important to a test. Let me explain what I mean with two examples.

Example Using Helper Method

public void CalcInterestRoundsToTenthPennies()
    decimal initialMoney = 100.00;
    decimal expectedInterest = 33.333
    InterestCalculator ic = GetTestInterestCalculator();
    decimal actualInterest = ic.CalcInterest(initialMoney);
    Assert.AreEqual(expectedInterest, actualInterest, 
      "CalcInterest did not round to a tenth of a penny correctly");

Example Without Helper Method

public void CalcInterestRoundsToTenthPennies()
    decimal initialMoney = 100.00;
    decimal interestRate = 0.3333333333;
    decimal expectedInterest = 33.333
    InterestCalculator ic = new InterestCalculator(interestRate);
    decimal actualInterest = ic.CalcInterest(initialMoney);
    Assert.AreEqual(expectedInterest, actualInterest, 
      "CalcInterest did not round to a tenth of a penny correctly");

Notice here that you can tell a lot more about what is going on in the second one, because you know what percentage is being used to calculate. You cannot tell that the first one is accurate since you can't see the percent. I recommend trying to keep the amount of values to a minimum and if you're writing your code well you'll have few enough dependencies that you will not have a problem. These helper methods as you can see make it so you will need to go to another location to see what was initially created. In some instances they are useful, but use them sparingly as they might hide away details.

Do Not Unit Test Third Party Frameworks

Make sure that what you're testing is part of your code and not someone else's. If you're testing code you have no access to you better not be keeping that around as an automated test. You're wasting your time if you're creating automated tests for this code. If you find a bug in the code you can tell someone about it, but you probably can't fix the code. If it is an open source project you're testing then go test the code in their test library and fix issues you find. You will be doing them and yourself a favor. Don't clutter your own test library.

Write Automated Tests Whenever You Are Curious

If I ever wonder how some piece of code or a class works or something, I could go write a simple application and test something out. I certainly do not waste my time though. It tends to be much faster just to write a test to answer my question or learn something new. If I want to try something out I just write a test. If it is an internal piece of code I go look at the existing tests, and if it is not I write a temporary one just to try something out.

Unit tests are quite useful for this sort of thing, and since I have keyboard shortcuts mapped to run them they're very fast. If you really want to test a lot, you need to start using them all the time. They become very easy to come up with and write once you practice them enough.

Time-Tested Testing Tips - Part 2

In the first part of this series of testing tips, I mentioned a couple of tips I believe to be quite useful. I am going to continue this series today by writing about a couple of more ways to write better tests. I also plan to give reasons for testing and describe different benefits of the practice as I go.

Test Driven Development

Yes, I am going to bring this up. Plenty of people have latched onto the idea that testing code helps make code better. A lot of people even believe that it makes the process of writing the code faster. I see a lot of people who are reluctant still to use test driven development. I know I am throwing around a buzzword… or maybe I mean buzzphrase since that’s actually three words.

I don’t plan on doing TDD justice here since I am trying to keep these tips relatively short. I just hope this is enough to inspire people to go read, learn more, and try some test driven development. I am going to give some quick reasons why developers testing their code should write the tests first.

  • You will not want to go back and write it later. Sometimes you are going to go back and write the tests for the code you have already written, but what happens if you decide you’re going to write a lot of code and then go back and add the tests. Now you’re talking about a lot of testing all at once. There is a good chance you’ll cut corners and maybe skip entire aspects of the testing. I know I would be tempted.
  • How do you know what kind of interface your new code needs if you’ve never used it? If you start by trying to use some code that does not exist yet, you’ll be deciding how you would want to use it. Now you’re probably thinking you could do that anyway. If you write code to use some new feature you will know the design is easy to use and work with. You just made it up and used it in the test. If you didn’t write the test you had to guess what interface you will want later.

Organize, Refactor, and Take Care of Your Tests

I recommend you repeat this daily, “My test code is just as important as my production code”. I think this is a very good point to remember when you’re writing tests. All of those principles you apply when writing production code should be followed with test code. DRY, SOLID, YAGNI, etc. are all important even with the testing code.

Obviously duplicating code can make your tests difficult to maintain. What if some business logic changes? If you were repeating yourself you now have the fun task of going through a dozen tests changing each one, but if you had not repeated the same code you might have been able to update one location in the test code. A lot of people are concerned when the line count of a single file gets large and they will refactor it into multiple manageable files. This same policy should apply to test classes. If you’ve ever gone into a test class with way too many classes, you probably know how difficult it can be to maintain.

Tests exist to make development easier, and if they become difficult to maintain then something needs to change. I certainly don’t advocate spending large amounts of time refactoring the tests, but since they are supposed to increase the longevity of the application they must also be maintained.

Adjust Your Style to Your Test Framework

I obviously recommend that everyone use a testing framework. There are plenty of them out there, and they supply a great deal of the tools you’ll need for testing. They come in all languages, flavors, and colors. You might look into these NUnit, MSTest, JUnit, CppUnit. What is important is that you make sure you know how your tools work so you can test best with them.

I will elaborate on a couple of examples and perhaps down the road I’ll give some more specific examples.

Some tools show you a list of test names, and only minor details about why the test failed. For this you usually need to go the a description view or something similar. In these cases it is important to name your tests effectively.

As an example if I have a method called Add and it takes two parameters a and b. I might write a test for that method. If I name my test TestAdd, and that test fails you know something is wrong in that method, but you do not know what failed. If I had instead made a few more specific methods you could glean more information from the test having failed. Some examples of tests I might create are AddTwoZerosShouldBeZero, AddNumberToZeroShouldBeTheNumber, AddPositiveNumbersTest, AddNegativeNumbersTest, etc.

Some parts I would lump together like positive numbers and negative numbers. It is important to handle a couple of different scenarios as well as the edge cases. I could have done negative and natural numbers and that would cover all numbers, but I wanted to make sure the edge case, zero, was handled correctly, so I test it separately.

People can argue back and forth all day long about whether you should have a lot of small tests or group them together, but this is what has worked well for me in the past and I hope it works well for you also.

Choosing A Dependency Injection Pattern

There are a few patterns you can follow when writing code which injects dependencies; constructor, property, and method injection. Which way is the best one to use? I don't really know for certain, but I can talk a little bit about the differences and some of the benefits of each. I am sure this behaves as most situations do with certain ones perform better in certain situations.

Constructor Injection

In this form of injection we pass the dependency into the object using its constructor. Before creating an instance of our object we have to get instances of all of the dependent objects required by the class and pass them in.

I really like this form of injection because it defines up from what is required to use the object. The constructor is saying up front, "these are what I need in order for you to create an instance of me, so if you don't have them bugger off".

public class Car
    private ITransmission _trans;
    // Constructor Injection
    public car(ITransmission trans)
        _trans = trans;

Property Injection

This pattern allows you to set the dependency after the instance of your object has been created. I shy away from this type simply because it concerns me that objects might not have their dependencies set if they're not required by the constructor.

I like using property injection in certain circumstances. I like using them in combination with constructor injection. I use them this way in instances where the dependent object might need to change.

public class Car
    // Property Injection
    private ITransmission _trans;
    public ITransmission Transmission
        get { return _trans; }
        set { _trans = value; }

Method Injection

If a dependency is really only needed by one method it is nice to put it in the method signature. This lets everyone know the method requires it. If we were using property injection we might have needed to know in advance to set the property. This type allows you to have one less property to set or one less parameter in the constructor.

Also if a method sometimes needs different instances of the dependency this is the way to go.

public class Car
    // Method Injection
    public void Shift(ITransmission trans, ShiftDirection direction)
        // do stuff here

Putting Them Together

As I said moments ago, I try to use these techniques collectively. It allows me to leverage the benefits of each. I think as a general rule you should try to tend towards one of them. I've seen people make great use of each of them.

If you can keep your dependencies to a minimum and localized to certain methods then method injection works pretty well. Property injection requires that you be more careful to make sure the dependencies are being set, but can eliminate a lot of clutter which can be found with method and constructor injection. Constructor injection is nice because it documents up front in the method signature what dependencies exist in the class.

Time-Tested Testing Tips - Part 1

These days more and more people seem to be testing. I admit I am one of the developers who has been writing unit, integration, acceptance, regression, and other tests. The idea of testing has been around for a long time, but it seems lately there has been a surge of people beginning to use them. Some are having great success and some are seeing their success fall away. Simply writing tests does not suddenly make great code.

Something I think everyone should know is that testing code is desired because it allows us a few benefits; the confidence that everything is working, the confidence that a bug has been eliminated, ease of maintainability, and extra documentation of a system written in code.

Tests as Documentation

I believe I've said plenty of times in the past that the tests you write become excellent documentation which can be used to demonstrate how different aspects of your system should be used. This is very useful for someone joining a project. If it is well-documented in its tests, learning how to work with the code is as easy as reading through the tests and seeing how the different objects are intended to interact. If you can't do this, you're probably not testing well.

A good measure of your application's testing is to have someone learn to use the system based solely on the tests. If the tests are written well enough, someone will be able to figure out how everything works and interacts.

This is one of my primary goals when testing an application. I want to make sure that things are clear, because when I come back to this code a month from now I will be that new developer on the project. I will need to know how to use the classes, interfaces, etc. and having it documented in working cases goes a long way.

How many tests should I write?

This is one of the most common questions asked by new testers. For now I will take the cowardly approach and say, "it depends". I've read posts from people touting the number of tests they've written. This is a new metric as if "line count" wasn't already bad enough. There is a balance here that we are looking for. Just with the line count.

If your line count is small you're application probably doesn't do very much and if it is large then your application might be cumbersome and difficult to maintain. When you don't have many tests your code is more prone to errors, but if you've written too many tests maintainability disappears. But wait! Didn't I say earlier that tests make code more maintainable. Well, yes I did, but if you write too many it becomes difficult to change the code. If you test every single possible minute little thing in your application you're going to have a heck of a time changing anything.

When you're writing tests make sure you have just enough to give yourself confidence that your code is working.

I highly recommend against ever setting code coverage or test count goals. If you set goals for these you're just creating incentives to write more tests than is required. Too many tests can create the same problems as too much code. Why? Because tests are code.

You need to treat your test code well. It needs to follow a lot of the same rules as the rest of what you write.

LINQ Your Collections with IEqualityComparer and Lambda Expressions

Anyone using LINQ to manipulate in-memory collections is probably also using plenty of lambda expressions to make things quite easy. These two additions were really meant for each other. One of our interns here recently ran into an interesting problem while using LINQ. As a relatively new user of .NET based languages, reference types caused him a bit of trouble.

The problem

While using the dot notation with lambda expressions, he was using the Except method in the following way.

List<MyObject> x = myCollection.Except(otherCollection).ToList();

Well the problem here is that these two collections contain "MyObject"s, and when it does the comparison it does so based on the reference. This means if those are separate but equivalent objects that the comparison will claim they are different.

He had unit tests making sure that the except statement worked, but was using the same instance of variables to Assert, so the tests claimed to work.

I told him the problem and mentioned that there was probably an overload of Except that allows one to specify how to do the comparison. I was correct, but the overload takes an IEqualityComparer object. I was hoping for a Func<x,x,bool> as the second parameter, so I did what I always do; I Googled to see if anyone knew an easy way to get that to work without doing extra work.

The Internet was kind enough to inform me that there was no built in way of handling this situation.

Building your own was the suggestion. It is a pretty simple class, so it can just be tossed somewhere to be reused easily. It could easily come up and be needed again.

public class LambdaComparer<T> : IEqualityComparer<T>
    private readonly Func<T, T, bool> _lambdaComparer;
    private readonly Func<T, int> _lambdaHash;

    public LambdaComparer(Func<T, T, bool> lambdaComparer) :
        this(lambdaComparer, o => 0)
    public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash)
        if (lambdaComparer == null)
            throw new ArgumentNullException("lambdaComparer");
        if (lambdaHash == null)
            throw new ArgumentNullException("lambdaHash");

        _lambdaComparer = lambdaComparer;
        _lambdaHash = lambdaHash;

    public bool Equals(T x, T y)
        return _lambdaComparer(x, y);

    public int GetHashCode(T obj)
        return _lambdaHash(obj);

Now that we have a nice, Generic, comparer which can take lambda expressions, we are all set to plug this in to the previous code.

List<MyObject> x = myCollection.Except(otherCollection, 
  new LambdaComparer<MyObject>((x, y) => x.Id == y.Id)).ToList();

// or

IEqualityComparer comparer = new LambdaComparer<MyObject>((x, y) => x.Id == y.Id);
List<MyObject> x = myCollection.Except(otherCollection, comparer).ToList();

I admit I am still kind of annoyed that there wasn't an overload which just took a Func<T, T, bool> or a Func<T, T, int>.

Either way, I hope this helps someone use LINQ a little more easily. I know of some alternate ways of solving this same problem. So if you think I should have solved this differently then blog it and link back here or just post a comment below.

Update 16 April 2009 - From a comment below

One commenter below posted a suggested extension method for use with this. He suggests using this nice extension method so you can hide away the fact that you're using the custom comparer class.

public static class Ext
    public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, 
        IEnumerable<TSource> second , Func<TSource, TSource, bool> comparer )
        return first.Except(second, new LambdaComparer<TSource>(comparer));

Thank you for the comment. I like the idea. It will very nicely hide away the fact that a silly comparer is needed.

We Slice Software Vertically Just Like Bread

Bread When working on a feature or some other aspect of a software project, it is important to figure out what piece you want to do at any given time. There are two primary routes you could take. Perhaps you want to go and create the whole UI, but have nothing wired up. Maybe you want to go and write all the business logic first, and you might want to go create the data layer and underlying infrastructure. If you do one of those then I will call you crazy.

I believe in vertically slicing an application. You never know at the beginning of a project what scope creep is going to occur, and you also don't know which aspects of your initial design will be completely unnecessary. One of the main reasons why so many people are against "big design up front" is because we don't know what we're going to need in the end.

If we're working in vertical slices, we can complete an entire piece of functionality that we know we need. This is why we work with vertical slices. We can stop at any time, and there are no unused pieces. Everything we've completed is there and working.

If we ignore how references in our application might be set up and just look at the structure of an application with a very simplistic view, we might say that there is a UI that calls some form of business logic which in some way talks to some kind of data.

Basic Structure of a Project


Say for example that we are going to work with a horizontal slice. Yes, plenty of people do this. I tried working on an application this way many years ago. So perhaps we are thinking, "hey, why don't we get the database and the data layer hashed out at the beginning then we can just write all the code on top of it later." After working on this for a while we might end up with something like this. The blue is the completed work.

Work Done Horizontally


Now for some questions.

  • How much can we show the customer? Nothing.
  • Are we sure we structured everything the way the customer wanted? No.
  • What if this is an open source project, maybe we want to encourage other developers to join the project. Are these developers able to see the structure of our application and how we want things to work? Well it looks like.... no.

Now what if we had done the same amount of work vertically? We might end up with something like this.

Work Done Vertically


Now assume that this is the same amount of work as if we had worked horizontally. Sure we have a lot less breadth, but the depth of our work is far greater. Now if we ask those same questions.

  • How much can we show the customer? Everything we've worked on.
  • Are we sure we structured everything the way the customer wanted? Yes, because the customer can see it and can tell us right now if we did something wrong. We are able to quickly respond to and fix the problem.
  • What if this is an open source project, maybe we want to encourage other developers to join the project. Are these developers able to see the structure of our application and how we want things to work? They can see everything we've done. Anyone hopping on this project would see the full structure and know how the layers are interrelated and would likely be able to add meaningful work to the project.

My Past Horizontal Mistake

So I mentioned early in this article that I tried horizontally working on a project once.  Yeah, that was a mistake. As you get to new aspects of a project a little thing called scope creep occurs. As you get to and think about new pieces of an application you realize new ways you can improve them, right? Well, this is another major problem with working horizontally. As I added new pieces, I came up with new stuff I wanted to do. New ways of doing things came to mind. Eventually I had scope creeped the data enough that I ended up giving up on the project.

I've recently started working on the project again, but this time I am of course working with vertical slices. I am going to make pieces just large enough to give me some value. That way at any point I could stop development and have a working tool. One which does something. Maybe not everything I want, but enough.

A Skill to Learn

Breaking tasks into thin vertical slices is difficult. Without advances in bread slicing technology, the processed, sliced bread from stores could never be so thin. It isn't easy to make thin slices, but the thinner the slice the better we are able to get the amount of bread we want. Perhaps we want 3 slices. Before we had these thin slices it might have been one and a half, but the thin slices make everything easier.

Some tasks look like they'll take weeks to complete. That my friend is not a task. We need to split that. There is probably some aspect of that which could be completed in a day. Maybe it wouldn't be in a shippable state, but there would be something that the customer could see. An initial bit working that is not the whole thing. This gives us two things. It shows the customer what we're working on, and it also gives them the chance to give us feedback. We can more easy adjust that small slice than if we had delivered the whole feature at once.

A Slicing Example

Assume we have a web site. We want to add user profiles to the site. Our customer comes along and says he wants the profile to have this information.

  • Full Name
  • Nickname
  • Location
  • Age
  • Gender
  • List of current and previous occupations
  • List of educational institutions
  • List of favorite games
  • List of favorite movies
  • List of favorite books
  • List of favorite songs
  • List of favorite musicians
  • List of favorite places
  • List of friends

If you went to do all of this at once it could take you a while. This is a good time to figure out some nice places to split things. An obvious split here is to do everything that is not complicated. For this we could say the top 5 ones we'll do. These don't have lists.

Slice 1: Create Full Name, Nickname, Location, Age, and Gender as a profile and create a view and edit page for them.

That slice is very manageable, and when you're done you can show the customer and make sure that is what they were expecting. Perhaps they wanted Full Name to be 3 separate pieces: First, Middle, and Last. Since we haven't done much, this is easy to change right now.

Now we might say that the next slice is the next item on the list. Why? Because we want to get one of the lists in place and the functionality set up and to the customer for feedback.

Slice 2: Add a list of current and previous occupations to the user profile.

Ok so we implement this basically as a list of strings. The user puts in the name of the occupation and adds more in the same way. We display this list of occupations on the profile page. Now when we show the customer this he says that he wants the list to intelligently suggest occupation names as the user types with previously used occupations. So now it is a bit more complicated, but we make the change. We then ask if the same will be done with the other lists, and the customer says "yes". Now we know how to do these next ones.

As we work through the next few slices, maybe the customer decides that we don't need both musicians and songs. The customer gets rid of musicians. Well we benefit here, because we hadn't put any work into that yet.

I really want to emphasize here that a slice should be small. Vertical slices are there so you always have a working product. At any moment you could stop. Maybe we stopped before doing the lists of things. We had a working solution at that moment. The other big reason we do vertical slices is so people can se what we've done and give us feedback. Customers might give you feedback on the UI, but until it is wired up and working the feedback isn't as useful.

Just In Time Properties

Properties with backing fields can easily be null. I often see properties which check the backing field to see if it is null. This is commonly done with an if statement with one line of initialization. One way to get around this is to use the coalescing operator in C#. If we use this in combination with an expressions, which might be a method, we are able to easily handle this property with one line.

Here is an example of what I am talking about.

private SomeType _someObject;
public SomeType SomeObject 
        return _someObject ?? (_someObject = giveMeSomeObject()); 

Notice how short and concise this is. I am able to with one line which is very clear handle this common scenario. Sure it doesn't always match this exactly, but I see plenty of properties people write where they do something similar.

I think that is very elegant and a lot nicer than doing this older style.

private SomeType _someObject;
public SomeType SomeObject 
        if (_someObject == null)
            _someObject = giveMeSomeObject(); 
        return _someObject;

Getting Around a Lack of Interfaces With Partial Classes

One pain point which comes along often when working with others' libraries are the classes that are not open and implementing interfaces. A lot of the classes we developers use every day implement no interfaces. Since the class is out of my control, I obviously cannot give it an interface, so I need some other way to work with it. This creates a problem when we need to mock out the class. There are ways in which we can get around this though.

Wrapping Classes

In my opinion, the most dependable workaround to be able to mock out and test a class is creating an interface-implementing wrapper around the class we want to mock and using that instead. This one works very well, but it forces you to create an interface and a class even though there is already a class in existence.

Partial Class Interface

As the name of this post says, partial classes can be very important when presented with this problem. If a class is not implementing an interface, but it is a partial class, you can give it an interface it is already implement.

If a class is partial you can give it an interface which defines the methods it already implements.

So now I am going to present an example. For this example, we will have a class called "BrendanMailer". This class is not implementing an interface, which means that if we want to remove this dependency we need to come up with some solution that lets us program against an interface.

public partial class BrendanMailer
    public void SendEmail()

    public void SomeNonImportantMethod()

For this we could obviously use the wrapper method, but we can also do something a lot easier. Thanks to the smart creator of that class, there is a partial keyword in there. This allows us to leverage a very powerful trick, because we can now create our own interface. The interface can include only the methods we want it to, which is in some ways better than if the interface had been predefined.

public interface IBrendanMailer
    void SendEmail();

So now I have a custom interface to work with and program against. I now just add that into another part of this partial class and tell that one I am implementing the interface. I don't have to implement the methods, because they already are implemented in the original part of this partial.

public partial class BrendanMailer : IBrendanMailer

In my production code I will inject the BrendanMailer class, and in the tests I will mock it out or use a fake or something. This is very powerful and doesn't clutter much at all, because I can hide this partial away in a folder in my project and ignore it for a long time.

Recent Article Writing

Over the past month, I've written a few articles for ASP Alliance. I now need to shamelessly plug my own stuff. If I didn't post this kind of stuff on my blog, I wouldn't really be doing my job. I wrote these articles so people could read them, and linking to them here should help with that. Enjoy.

Standard Type Casting and "as" Operator Conversions

In early February, I wrote this article, which discusses in fairly easy to understand language when, why, and how to use each of these types of conversion. I am hoping that anyone who doesn't know the difference or doesn't know when to use each one, learns a little bit more about that from this article. I tried to keep things fairly basic, so people could really understand this well.

Read more about Type Casting and "as" Operator Conversions

Using Objects Instead of Enumerations

I love enumerations, but they have caused me plenty of pain in the past. Why did they cause problems for me? Well, that is because I shouldn't have been using enumerations. I've seen plenty of people doing the same thing. Sometimes you really just need to have a class instead of an enum. However, if you really do need a restricted set of values, you can use private constructors to create the only allowed instances of this object as public properties. I tend to move to this type of object as soon as I need a description, a friendlier name, or any additional logic for my enumeration.

Read more about Using Objects Instead of Enumerations

Beginning Test Driven Development

Lately a lot of people have been trying to learn how to test their applications, but I think there is a fairly significant learning curve preventing people from getting to that point. I am planning on writing some related articles to this one which start pulling together the different aspects of testing. I will probably be discussing Dependency Injection, Mocking, and Inversion of Control at some point. For this article I focused mainly on how to write tests. I know a bunch of people who are trying to get started testing, but don't know how or what to test.

Read more about Beginning Test Driven Development

Let me know what you think about these articles. As long as you're nice about it, I always like getting feedback; even feedback pointing out problems in the articles.

Treat Your Tests Well

There are a lot of people starting to test, and some of them seem to have this misconception that test code is less important because it is, "just test code". I don't know how they come up with this crazy idea, but it creates some pretty ugly tests. When following the principles of Test Driven Development, it is important to realize that you will come back to these tests. You will look at them when they fail, you will adjust them when logic changes, and others will read them especially when they are trying to learn the system.


At some point you could perform maintenance on any piece of code in your application. THIS INCLUDES YOUR TESTS. When you need to go in and change them it better be easy. There better be code reuse, variable names better be descriptive, and you really need to have things organized well enough for you to find what you're looking for.

Single Responsibility Principle

The Single Responsibility Principle is a commonly followed principle when writing code, but I've seen people disregard it when writing tests. Your tests are extremely important. Don't make huge catchall test classes. Keep your test classes small and manageable. Each one should contain only a related group of tests. You will come back to these if you're testing correctly, and when you make changes you will write new tests or adjust old ones. Don't think for one second that you will never see your test classes after you write them. When you add new features and adjust old ones, you will need to open these files again.

Test code is a first class citizen in your project. It is every bit as important as the rest of the project. Treat it as such or it will bite you back.

One Way Tests Differ From Other Code

With tests, the specific details are a little bit more important than in other code. You still need code reuse for obvious reasons, so what do I mean here? All I am saying is that you don't want to hide things away in mysterious methods. Normally we extract methods to hide the details of some operation we are performing. We should be doing the same thing with test code, but we need to make one exception. When the details of that method are what you're testing, you must have them in your test.

In some instances you have an object with involves some complicated or at least tedious initialization, so you would want to hide that away in a method. For testing, however, it is important that you define the details of that initialization in the test method if they are important to the test.

As an example, we can say that we are working on a game, and we keep a Points property on our Player object. Maybe we want to make sure that after some action that would lose a player points, he doesn't go below a negative number. So we have a method that creates a player object for us. The problem is that we don't know what his initial points are set to if we don't either make that a parameter in the initialization method or set it after initialization. In some way we need to make sure that we define this in our test method.

Never ever let details you depend on be hidden away in some method where you can't see them in your test.

I've seen plenty of people use helper methods to initialize variables and such for their tests. This is a very bad idea if any of that information is important to that specific test. Only hide away unimportant details. For instance you might hide away the initialization of your mocked objects, but you would keep the player's points you will be Asserting the value of front and center. If values are being initialized in a non-test method you should be able to change those tests safely without causing problems.

Treat your tests well and they will be there to help you.