How to mock a JPA Repository to use it for test with Junit?

Mo Elkinani :

I can't do the save to the objects after modifications.

I'm setting attributes of an object to a new values , when I'm looking to save , I receive a NullPointerException.

/* La méthode à tester */
public Rem afterInitRem(Rem rem) {

    /** Initialize regles with status MISSING **/
    List<Regle> regles = rem.getRegles();
    Regle regle = new Regle();
    regle.setCode("REGLE1");
    regle.setStatus(RegleStatus.MISSING);
    regles.add(regle);
    return remRepository.save(rem);
}

/*Le test*/
@Mock
private RemRepository remRepository;

@BeforeEach
void beforeEachTest() {
    rem = new Rem();
}

@AfterEach
void reInitVar() {
    beforeEachTest();
}

@Test
public void afterInitRemTest() {
    target.afterInitrem(rem);
    when(remRepository.save(any(Rem.class))).thenReturn(rem);
    ArgumentCaptor<Rem> argument = ArgumentCaptor.forClass(Rem.class);
    verify(regleRepository).save(argument.capture());

    assertEquals("REGLE1", argument.getValue().getRegles().get(0).getCode());
    assertEquals(RegleStatus.MISSING, argument.getValue().getRegles().get(0).getStatus());
    assertEquals(1, argument.getValue().getRegles().size());
}

Je fais le debug, je vois que les sets sur les attributs ça passent, le problème est au niveau du return remRepository.save(rem);

Maciej Kowalski :

As you are using Junit5, make sure you have either of these in your code to initialize the mocks:

@ExtendWith(MockitoExtension.class) on the test class

or

@BeforeEach
void beforeEachTest() {
    MockitoAnnotations.initMocks(this);
    rem = new Rem();
}

Also, you need to make sure that you have injected your mock manually or by using the @InjectMocks annotation into the SUT.

And finally, make sure you do all the mock set-up before calling the actual SUT method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166914&siteId=1