Marco Poloe
Marco Poloe

Reputation: 269

JUnit - Test class instantiation with objects in parameters

I am very new to JUnit testing and I am trying to understand how to test the instantiation of an class.

Let us say that I have the following ToyBox class which needs an ArrayList<Toy> in order to be instantiated. This list of toys is created on another part of the program, of course, but I do not understand very well where I should create it in order to unit test ToyBox.

ToyBox Class

public ToyBox(ArrayList<Toy> toyList){
    this.toys= toyList;

    for (Toy toy: toyList) {
        checkToy(toy);
    }
}

private void checkToy(Toy toy){
    if (toy.isRed()){
        this.numRed += 1;
    } else {
        this.numBlue += 1;
    }
}
public int getBlues(){
    return this.numBlue;
}

ToyBoxTest

public class ToyBoxTest {

    @Test
    public void getNumBlues() throws Exception {
        // assert that num blues corresponds
    }

Where should I instantiate the ToyBox class in order to perform the getNumBlues() method?

Should it be like this?

public class ToyBoxTest {
    ArrayList<Toy> toyList = new ArrayList<Toy>();
    Toy toy1 = new Toy("blue", "car");
    Toy toy2 = new Toy("red", "bike");
    toyList.add(toy1);
    toyList.add(toy2);

    @Test
    public void getNumBlues() throws Exception {
        // assert that num blues corresponds
        ToyBox box = new ToyBox(toyList);
        assertEquals(1, box.getBlues());
    }

Basically, my question is where and how should I create the arraylist of objects needed to test a class that depends on that created list.

Upvotes: 3

Views: 3457

Answers (1)

Mureinik
Mureinik

Reputation: 312319

Most tutorials will state that the best practice is to instantiate the object you're about to test in a setup method (a @Before method in JUnit's terminology). However, your usecase doesn't fit this pattern well. As your constructor holds all the logic, you should instantiate the object in the test itself, and then assert that getNumBlues() and getNumReds() return the correct results. E.g.:

@Test
public void bothColors() throws Exception {
    ArrayList<Toy> toyList = new ArrayList<>(Arrays.asList
        new Toy("blue", "car"),
        new Toy("red", "bike"));
    ToyBox box = new ToyBox(toyList);
    assertEquals(1, box.getBlues());
}

@Test
public void justBlues() throws Exception {
    ArrayList<Toy> toyList = new ArrayList<>(Arrays.asList
        new Toy("blue", "car"),
        new Toy("blue", "bike"));
    ToyBox box = new ToyBox(toyList);
    assertEquals(2, box.getBlues());
}

// etc...

Upvotes: 2

Related Questions