Lucas
Lucas

Reputation: 1271

How can I avoid repeated inserts in Java Tests

How can I avoid the repeated test when I need to test the insert of a child entity in a Integration Test????

Use case:

I have a Person entity (parent) and a Phone entity (child). I need to persist a Phone before persist a Person but if I have a entity with a lot of child, my test will be a monster of duplicated code!!!!

I need something like:

public class TestPerson {

    public void should_insertPerson_and_find(){
        //I need to call should_insertPhone_and_find() to insert a Phone before insert people, because of dependency.....
        //... run test
    }

}

public class TestPhone {

    public void should_insertPhone_and_find(){
        //... run test
    }

}

Can someone sugest any API for this? Can JUnit do this?

Upvotes: 1

Views: 85

Answers (3)

Lucas
Lucas

Reputation: 1271

The best way I found it is the mkyong dependency test article!!!!

Thanks for the answers guys!!!

Upvotes: -1

boly38
boly38

Reputation: 1955

Any test should stay easy to read. Here is what I suggest.

// given
cleanTestPersonsAndPhones();
Phone tphone = createTestPhone ("testShouldA");
Person tperson = createTestPerson(tphone);

// when
// should find tphone or tperson relation(s)

// then
// verify find result (s)
 cleanTestPersonsAndPhones();

I m not fan of using @before and filtering by method name because test is less easy to re-read...

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298908

Basically the options are:

  • Have a common abstract superclass with a @Before method that does the initialization
  • Use JUnit Rules
  • Create a Utility method in another class and call the method from @Before methods in both classes

Upvotes: 1

Related Questions