Mo Elkinani
Mo Elkinani

Reputation: 53

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

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.

/* The method to be tested */
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);
}
        
/*The 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());
}

I was debugging, and I saw that the attributes were set, the problem is with return remRepository.save(rem);

Upvotes: 2

Views: 10371

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26512

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.

Upvotes: 1

Related Questions