简体   繁体   中英

Java panacheQuery test throws nullpointer exception

I have a function that uses panacheQuery. This also works as intended when I test it manually. But when I write a test and execute it, I get a null pointer exception.

The test looks like this:

  void testFindByNameAndTag() throws ApplicationException {
    final ImageRepository repo = mock(ImageRepository.class);
    final PanacheQuery<ImageBE> panacheQuery = mock(PanacheQuery.class);

    when(repo.findByNameAndTag(anyString(), anyString())).thenCallRealMethod();
    when(repo.find(anyString(), anyString())).thenReturn(panacheQuery);
    when(panacheQuery.firstResultOptional()).thenReturn(Optional.of(new ImageBE()));

    final ImageBE result = repo.findByNameAndTag("name", "tag");
    assertNotNull(result);
  }

The findByNameAndTag function in the ImageRepository looks like this:

@ApplicationScoped
public class ImageRepository implements PanacheRepositoryBase<ImageBE, Long> {

  private static final Log LOG = LogFactory.getLog(ImageRepository.class);

  public ImageBE findByNameAndTag(String name, String tag) throws ApplicationException {
    return find("name = ?1 and tag = ?2", name, tag)
            .firstResultOptional()
            .orElseThrow(
                    () ->
                            new ApplicationException(SOME_ERROR_CODE, SOME_ERROR_MESSAGE));
  }

}

Output of the test:

在此处输入图像描述

The exception seems to be throwed at.firstResultOptional. Did I do something wrong with the mock or the when uses in the test?

Thanks in Advance.

Try to add a @QuarkusTest annotation above your test class

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