Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit test cases for custom method

Tags:

java

junit

I'm studying for my first job interviews as Junior Java Developer and right now I'm trying to learn JUnit test cases. This is an example that I encountered and I must say it's really tricky for me (it's abstract code so I have no idea how to test it).

public class JuiceMaker {

  public Juice makeJuice(final List<Fruit> fruits) throws RottenFruitException {
    for (final Fruit fruit : fruits) {
      if (FruitInspector.isFruitRotten(fruit)) {
        throw new RottenFruitException(fruit.getName() + “ is rotten. Cannot make juice.”);
      }
    }

    return Juicer.juice(fruits);
  }
} 

The only example I managed to create myself is this one:

JuiceMaker jm = new JuiceMaker();

@Test
public void isThrowingException() {
//when
  try {
      jm.throwsRuntime();
      Assert.fail("Expected exception to be thrown");
  } catch (RottenFruitException e) {
//then
      assertThat(e)
          .isInstanceOf(RottenFruitException.class)
          .hasMessage((fruit.getName() + " is rotten. Cannot make juice.");
  }
}

Any tips of what kind of tests I can perform on this piece of code? Thanks a lot for your help!

like image 248
Vinci Avatar asked Mar 09 '26 18:03

Vinci


2 Answers

Welcome to JUnit, and good luck with your interviews!

First question to ask is what is the contract offered by this class? It takes a list of fruit, tests if any of the fruit are rotten, if so it throws an exception, otherwise it juices them. You can assume the "juice" method is tested elsewhere.

To me, that suggests these tests:

  • List with single good fruit
  • List with single rotten fruit
  • List with several good and one rotten fruit
  • Empty list

You could also test for null and invalid values, but that might be overdoing things just now.

Once you've decided what to test, then you can start thinking about implementing them. Looks like your implementation has a couple of errors, but you're heading in a good direction. You might find JUnit's "expected" parameter useful for testing for exceptions.

like image 103
hugh Avatar answered Mar 12 '26 06:03

hugh


You seem to be instructing the JuiceMaker instance in your test to throw the exception to verify you can catch it.

You have to answer yourself whether that alone will exercise the loop iterating through the list of Fruit and the if() statement.

You can influence the JuiceMaker.makeJuice() better by passing different lists (null, empty, with no rotten fruit, with rotten fruit).

This way you are not forcing any exceptions but causing them - which exercises more paths through your code under test.

If you exercise the above scenarios, you should have a very decent test coverage of your method.

Hope this helps!

like image 20
diginoise Avatar answered Mar 12 '26 08:03

diginoise