How much object initialization should I do in unit tests?

Let say I am unit testing a method that returns the count of cars in my garage so I have a method like this:

public class Garage {
    public long numberOfCarsInGarage() {
        return cars.size();
    }
}

From the test class:

@Test
public void numberOfCarsInGarage_returnsCount_whenCarsHaveBeenAddedToTheGarage() {
    Garage garage = new Garage();

    Car firstCar = new Car();
    Car secondCar = new Car();
    Car thirdCar = new Car();

    garage.addCars(firstCar, secondCar, thirdCar);

    assertEquals(3, garage.numberOfCarsInGarage());
}

Each car object has many properties to set, but I don't need to set them in order for the test to pass. Am I right that I should do the least possible code in the test to make it pass/fail? I am not doing anything wrong here by not setting dummy data on the car objects in the test?

Answers


For your use case as described, it seems fine not to set dummy data. It really depends on the project. I'm working on testing a complex distributed system involving 5 servers and multiple processes on each server. Some of my tests handle small parts of that, but some are end to end tests for the entire system. In my case, most of my test framework is setting up the environment. The general rule though is that you should set up enough so that your test is likely to capture failures. Whenever you find things that your test cases doesn't capture because it didn't set up enough, considering setting up more so that the test case will capture that in the future. Note that you're trying to balance test cases covering likely problems against making them simple enough to write that you can efficiently write them.


If you're unit testing numberOfCarsInGarage() it means you want your test to fail only when something in that method goes wrong, then you should try to isolate its invocation from the rest of the stuff in the class.

I suggest avoid invoking addCars(), instead I would create a list of mock cars and I'd set it in the SUT using reflection.


Need Your Help

LDAP: How to get list of users from a specific group using C#?

c# active-directory ldap

So I'm new to LDAP, and I'm having trouble finding a solid resource.

Implementing an interface using an asynchronous WCF service?

wcf asynchronous interface

I am trying to figure out if it is possible to implement a .NET interface, where the interface method has to return something and you are implementing that particular interface method with an