vendredi 8 novembre 2019

Mockito NullPointerException - Not recognizing repository

I'm having trouble figuring out why Mockito is throwing a NullPointerException when I'm telling the mock to return true.

Here is my JUnit Test:

public class PizzaValidatorTest {

  private Pizza meatPizza;

  private PizzaValidator validator = new PizzaValidator();

  @MockBean
  private IngredientRepository ingredientRepository;

  @MockBean
  private PizzaSizeRepository pizzaSizeRepository;

  @Before
  public void setUp() throws Exception {

    meatPizza = new Pizza();

    validator = new PizzaValidator();
  }

  @Test
  public void validateValid() {
    when(ingredientRepository.existsById(any())).thenReturn(true);
    when(pizzaSizeRepository.existsById(any())).thenReturn(true);
    assertTrue(validator.validate(meatPizza));
  }
}

The PizzaValidator class is implemented below:

@Controller
public class PizzaValidator implements Validator<Pizza> {

  @Autowired
  IngredientRepository ingredientRepository;

  @Autowired
  PizzaSizeRepository pizzaSizeRepository;

  @Override
  public boolean validate(Pizza entity) {
    return validatePizza(entity);
  }

  private boolean validatePizza(Pizza pizza) {
    return validPizzaSize(pizza) && validIngredients(pizza);
  }

  private boolean validPizzaSize(Pizza pizza) {
    return pizzaSizeRepository.existsById(pizza.getSizeDesc().getId());
  }

  private boolean validIngredients(Pizza pizza) {
    for (Ingredient ingredient : pizza.getIngredients()) {
      if (!ingredientRepository.existsById(ingredient.getId())) {
        return false;
      }
    }
    return true;
  }
}

For some reason it seems like Mockito isn't connecting the mock repository with my class repository, but I can't figure out why. Any help is appreciated. Thanks.

Aucun commentaire:

Enregistrer un commentaire