Java – JUnit test cases for custom methods

I'm studying my first job interview as a junior java developer, and now I'm trying to learn JUnit test cases This is an example I encountered. I must say it's really difficult for me (it's abstract code, so I don't know 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've 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.");
  }
}

Tips on what tests can I perform on this code? Thank you very much for your help!

Solution

Welcome to JUnit and wish you a smooth interview!

The first question to ask is what is the contract for this course? It needs a fruit list to test whether any fruit rots. If so, it will cause abnormalities, otherwise it will squeeze juice You can assume that the "juice" method has been tested elsewhere

For me, this shows that these tests:

>List a single good fruit > list a single rotten fruit > list several good and one rotten fruit > empty list

You can also test for null and invalid values, but this may just be excessive

Once you decide what to test, you can start thinking about implementing them It seems that there are several mistakes in your implementation, but you are moving in a good direction You may find JUnit's "expected" parameter useful for testing exceptions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>