Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit: Testing If-clause in method

Tags:

java

junit

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?

like image 807
JavaNullPointer Avatar asked Jun 01 '26 04:06

JavaNullPointer


1 Answers

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

like image 145
Nir Levy Avatar answered Jun 03 '26 18:06

Nir Levy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!