Reputation: 55
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.
Upvotes: 2
Views: 779
Reputation: 40048
You should not create the PizzaValidator
using new
keyword, you should @Autowire
it in the test
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class PizzaValidatorTest {
private Pizza meatPizza;
@Autowire
private PizzaValidator validator;
@MockBean
private IngredientRepository ingredientRepository;
@MockBean
private PizzaSizeRepository pizzaSizeRepository;
@Before
public void setUp() throws Exception {
meatPizza = new Pizza();
}
@Test
public void validateValid() {
when(ingredientRepository.existsById(any())).thenReturn(true);
when(pizzaSizeRepository.existsById(any())).thenReturn(true);
assertTrue(validator.validate(meatPizza));
}
}
Upvotes: 2