What's the proper way to test multiple constructors in Junit?

Pickle_Jr :

Should I ignore unit tests for new constructors? Should I make a new Test class for the different constructors and just copy the tests? The tests themselves did not change. It would be nice if there was a way to run every test just with different constructors. To visualize what's going on, I added code below.

I had a class that looked like this:

public class Foo {
    public Foo() {...}

    public void doStuff(){...}
    public void doThing(){...}
}

And I have a test class that looked like this:

public class FooTest {
    Foo foo;

    @Before
    public void setUp() {
        foo = new Foo();
    }

    @Test
    public void fooCanDoThing() {
        foo.doThing();
        assertThat(...);
    }

    @Test
    public void fooCanDoStuff() {
        foo.doStuff();
        assertThat(...);
    }
}

I recently had a task that included adding more constructors to my foo class

public class Foo {
    ...
    public Foo(String bleh) {...}
    public Foo(String bleh, String blah) {...}
    ...
}

What is the best way to go about testing with multiple constructors?

Edit: To clear up some things, foo extends thing

public class Foo extends Thing {...}

Lets say that Thing has and handled function of getBlah and I already tested for getBlah. But now, I can actually set my own "blah."

Maciej Kowalski :

You should be testing behavior of the SUT in your test class.

If that additional constructor param introduces a new behavior to your class then you should create a test for it with a meaningful name:

shouldDoThingXXX_givenBleh()

shouldDoThingYYY_givenBlehAndBlah()

So most likely if you only set one variable, then your current tests will run as before but does the introduction of a an additional one introduces new behavior paths and different possible outcomes of certain functionalities?

If yes, then you should exhaust them with additional clearly named tests.

Summing up adding a new constructor does not mean, the double amount of existing tests, it may but it depends on the introduces / altered behavior of the SUT.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=101251&siteId=1