简体   繁体   中英

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.

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));
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM