Reputation:
very new to writing unit tests. can someone help me write a test for this
public List<PspTransaction> mapToDomainList(List<PspTransactionEntity> entityList) {
List<PspTransaction> domainList = new ArrayList<PspTransaction>();
for (PspTransactionEntity entity : entityList) {
domainList.add(map(entity, new PspTransaction()));
}
return domainList;
I want to know which things are good to test and an easy guide so I can learn for the future. Futhermore, I really want to know how to see if domainList is returned. is it assertTrue?
Upvotes: 2
Views: 1081
Reputation: 2826
I would encourage you to try to think of the outcome you want to test first and then write some code to make the test pass (TDD). This can help you with developing good interfaces and designing easily understood classes that you may even be able to re-use.
A couple of rules of thumb here are that you want your classes to have one responsibility and your methods to do one thing--in essence, it's the KISS principle, but with some specific design hints. Also, I like to think of tests for behavior rather than tests for methods--it's a subtle difference which I will find difficult to explain!
Here I have a method to test before I have thought about what I really intend for the system to do, so I find it harder to work this way, but I'll share my thoughts. I like to use AssertJ assertions.. I'm just winging this, so it hasn't seen a compiler.
import static org.assertj.core.api.Assertions.*;
...
private TestSubject testSubject = new TestSubject(); // instance of the class under test (you omit the actual class name)
...
@Test
public void should_return_empty_list() {
// Arrange
List<PspTransactionEntity> input = new ArrayList<PspTransactionEntity>();
// Act
List<PspTransaction> mapResult = testSubject.mapToDomainList(input);
// Assert
assertThat(mapResult.size()).isEqualTo(0);
}
@Test(expected=java.lang.NullPointerException.class)
public void should_throw_null_pointer_exception() {
// Act
List<PspTransaction> mapResult = testSubject.mapToDomainList(null);
}
So, I guess I would want tests along those lines if I'm working backwards from the code to the tests. Think of the happy path but also your edge cases like what should happen when you pass null, etc. Does it make sense? Hope it helps!
Upvotes: 1
Reputation: 6188
Generally speaking there are several things you can test here.
map
function.null
to the function.Methods that will help you in these tasks would be:
ExpectedException
with the type of Exception you're expecting).Upvotes: 1
Reputation: 2133
Looks like domainList
will always be returned since you just create a new one inside the mapToDomainList
method. So you need to check if it is not empty with something like assertFalse(returnedDomainList.isEmpty());
This will work if entityList
is not empty.
If entityList
is empty you can assert that your returned list is as well empty.
Upvotes: 0