Reputation: 1960
I have to implement a way to test the different methods of an application. I was collecting information about JUnit because to be the most famous way to properly test the methods of an application but I have many questions and I need answer that I can't find.
So I have the following JUnit test, the easier I could think of:
public class Civilian {
private final String firstName;
private final String lastName;
private final int birthDate;
public Civilian(String firstName, String lastName, int year) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = year;
}
public String getFullName() {
return firstName + " " + lastName;
}
}
And the test class:
public class CivilianTest {
@Test
public void getFullNameTest() {
Civilian civ = new Civilian("bob", "Reynolds",1997);
Assert.assertEquals("bob Reynolds", civ.getFullName());
}
}
In this example I have to know the result of the getFullName methods to compare it in the assertEquals() methods. But how could this kind of test guarantee that this method will work in any case?
In the application I have to work on, they use a lot of data coming from different database where this data will be modified trough the method and return this data modified.
The thing is that it's hard to know the result of this data before I used the method on it. Is JUnit only used like this? How could I test multiple uses of this same method on this same data?
Upvotes: 0
Views: 332
Reputation: 106400
There are a few principles of tests that you should bear in mind:
For your getFullName()
method, I see four distinct cases that are worth examining:
firstName
and lastName
are not nullfirstName
is null and lastName
is not nullfirstName
is not null and lastName
is not nullfirstName
and lastName
are nullIf you cover these cases then it shouldn't matter what actual live data you pump into it; you've tested the four possible states that this method can encounter, and hopefully you make sensible choices around what to do in the stranger of these cases.
The main thing is that you may be conflating unit test with end-to-end test, in which one only looks at the small unit and ensures that it behaves well, whereas the other looks at the entire application (still with mock data, but substantial amounts of data nonetheless) and ensures that it behaves as one cohesive unit. Just remember: you're testing the unit of code here, and not the whole system through this method.
Upvotes: 1