Home > Mobile >  Junit Test: findById method of the Repository
Junit Test: findById method of the Repository

Time:09-24

I am new in Junit tests and I have a question about it. Here you can see the method findById in my service class:

@Service
public class DefaultQuarterService implements QuarterService {

    private final QuarterRepository quarterRepository;

    public DefaultQuarterService(QuarterRepository quarterRepository) {
        this.quarterRepository = quarterRepository;
    }

    @Override
    public QuarterEntity findById(int id) {

        return quarterRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException(String.format("Quarter does not exist for id = %s!", id)));
    }
}

And here is my QuarterRepository:

@Repository
public interface QuarterRepository extends CrudRepository<QuarterEntity, Integer> {
}

And here is my Junit implementation for this method:

@MockBean
private QuarterRepository quarterRepository;

@Test
public void throwExceptionWhenQuarterIdNotFound() {
    int id = anyInt();
    when(quarterRepository.findById(id))
            .thenReturn(Optional.empty());
    assertThatAnExceptionWasThrown(String.format("Quarter does not exist for id = %s!", id));
}

public void assertThatAnExceptionWasThrown(
        String errorMsg
) {
    expectException.expect(RuntimeException.class);
    expectException.expectMessage(errorMsg);
}

Unfortunately test doesn't pass. Here the error in terminal:

java.lang.AssertionError: Expected test to throw (an instance of java.lang.RuntimeException and exception with message a string containing "Quarter does not exist for id = 0!")

Maybe it is so simple but I can not see what I am missing. I would be so happy if you can direct me. Thanks a lot!

CodePudding user response:

As you mock your Repository it will return with Optional.empty() correctly, I think you should call your service's (which is Autowired) findById method. It will throw the exception actually.

CodePudding user response:

First issue

In the assertThatAnExceptionWasThrown method you expect RuntimeException BUT in the service class you throw EntityNotFoundException, So I guess you should expect EntityNotFoundException in your test case.

Second issue

After this part of the code.

 when(quarterRepository.findById(id))
            .thenReturn(Optional.empty());

Why didn't you call your service method (findById)? When you are returning the empty value, you should verify your condition with the service method you want to test it. It should be something like this.

assertThatThrownBy(() -> defaultQuarterService.findById(id))
        .isInstanceOf(ApiRequestException.class)
        .hasMessageContaining("PUT_YOUR_EXCEPTION_MESSAGE_HERE");

This is a good sample for unit-test in the spring boot. You can check it out. Link

Try the above solutions and let me know it has been fixed or not. Good luck

  • Related