Skip to content
Advertisement

What is the best practice for using the same create object methods for the test classes

I have 2 unit test classes (ATest and BTest) for 2 classes (A and B). My classes:

public class A {

    public C convert(User user) {
        ...
    }
}
public class B {

    public D getD(User user) {
        ...
    }
}

So 2 classes methods need a User object as a parameter. I have the same method for generating a User in Test classes:

private User getUserForTest() {

        User user = new User();
        
        ...
        ...
        ...

        return user;
} 

getUserForTest method too long. I don’t want it to duplicate. My question is what is the best practice for using the same getUserForTest for ATest and BTest classes.

Advertisement

Answer

You are looking for what is called Test Fixtures.

You could use a third class with some static methods to create the test fixtures (things that you are not testing, but are using for your tests).

public class TestHelper{ //or a more specific name would be nice if possible
 
 public static User generateUser(/*add variables if required*/){
 User user = new User();
   ...
   return user;
 }

}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement