For my application I have a function handler like that:
class MyFoo {
private MyFoo2 myFoo2 = new MyFoo2();
public void handler(Object o) {
if (o.getName().equals("Name1")) {
myFoo2.doSomeStuff1(o);
} else if (o.getName().equals("Name2")) {
myFoo2.doSomeStuff2(o);
}
}
}
class MyFoo2{
List<Object> objectList=new ArrayList<>();
public void doSomeStuff1(Object o){
//prepare Object o I
objectList.add(o);
}
public void doSomeStuff2(Object o){
//prepare Object o II
objectList.add(o);
}
public getObjectList(){
return objectList;
}
}
Now I want to test my function handler with JUnit. To test it, should i have to get the objectList from my MyFoo2 and check the entry or is there another way to check a function like that?
What is here a good way for testing?
Are test like that unnecessary?
Since you ara talking about unit test, the correct way to test is should be without MyFoo2
You are testing MyFoo1, so you can mock MyFoo2 and use it just to verify the execution happens. something like:
public class MyFoo1Test {
@Mock private MyFoo2 mockMyFoo2;
@InjectMocks
private MyFoo1 myFoo1 = new MyFoo1();
@Test
public void testHandlerName1() {
Object o = new Object("Name1");
myFoo1.handler(o);
verify(myFoo2).doSomeStuff1(o);
}
@Test
public void testHandlerName2() {
Object o = new Object("Name2");
myFoo1.handler(o);
verify(myFoo2).doSomeStuff2(o);
}
@Test
public void testHandlerOtherName() {
Object o = new Object("OtherName");
myFoo1.handler(o);
verifyZeroInteractions(myFoo2);
}
}
Unit tests for MyFoo2 should be done seperatly, and in there you should test the doSomeStuff methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With