Matthew
Matthew

Reputation: 15662

Organizing test in unit testing

I'm learning about unit testing, and I'm trying to understand where the pieces fit together.

Say I have something like:

public class CarTest {

    public CarTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of toString method, of class Car.
     */
    @Test
    public void testToString() {
        System.out.println("toString");
        Car instance = new Car(1, 2);
        String expResult = "1/2";
        String result = instance.toString();
        assertEquals(expResult, result);
    }
}

Say I have different Cars I need to test. Maybe the constructor call of one should have two negative numbers, etc. Where do the different "cases" go? I need to run testToString() on each of them, and I don't want to copy and paste 5 different cars / asserts for each method I need to run. Do I store them all in an array of the test class and have them built in each setUp() or something?

Upvotes: 2

Views: 275

Answers (1)

The Nail
The Nail

Reputation: 8500

Create a Parameterized Test. This allows you to run one test class on different items:

http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/

This one is even about cars:

http://techinsides.blogspot.com/2010/08/dont-repeat-yourself-junit-4s.html

Or without using the Parameterized runner:

Parameterized jUnit test without changing runner

Upvotes: 1

Related Questions