NullPointerException when running JUnit test with TestEntityManager in Spring Boot

Alfonso Pimienta

Error Description: When running the test findByEmail in the ClientRepositoryTest class, a NullPointerException occurs with the message "Cannot invoke org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.persist(Object) because com.saajf.manager.eewaapro.ClientRepositoryTest.entityManager is null."

Code Snippet:

package com.saajf.manager.eewaapro;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;

import com.saajf.manager.eewaapro.domain.entities.Client;
import com.saajf.manager.eewaapro.infrastructure.repositories.ClientRepository;

@DataJpaTest
class ClientRepositoryTest {

    @Autowired
    private ClientRepository clientRepository;

    private static TestEntityManager entityManager;

    @Test
    void findByEmail() {
        Client client = new Client();
        client.setId(1L);
        client.setCompanyAddress1("cr 54 # 143a - 90");
        client.setCompanyName("cualquier cosa");
        client.setCompanyType("Software");
        client.setCompanyPhone1("3165476589");
        client.setEmail("[email protected]");
        client.setIdentification("123456789");

        // Guardar el cliente utilizando el entityManager persistente
        Client savedClient = entityManager.persist(client);

        // Limpiar el entityManager para asegurar que se recargue el cliente desde la
        // base de datos
        entityManager.clear();

        // Realizar la búsqueda del cliente por email
        Client foundClient = clientRepository.findByEmail(savedClient.getEmail());

        assertThat(foundClient).isEqualTo(savedClient);
    }
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- Parent -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.11</version>
        <relativePath/>
    </parent>
    <groupId>com.atukaa.eewaapro.manager</groupId>
    <artifactId>eewaapro-manager</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eewaapro-manager</name>
    <description>Manager component for the Atukaa Eewaapro Service</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <!-- Dependencies -->
    <!-- Add your dependencies here -->
    ...
    <!-- Build -->
    <!-- Add your build configuration here -->
    ...
</project>

Stack Overflow Question: Title: NullPointerException when running JUnit test with TestEntityManager

I'm experiencing a NullPointerException when running a JUnit test with TestEntityManager. The error message states: "Cannot invoke org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.persist(Object) because com.saajf.manager.eewaapro.ClientRepositoryTest.entityManager is null."

contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]] [[1;31mERROR[m] [1;31mTests [0;1mrun: [0;1m1[m, Failures: 0, [1;31mErrors: [0;1;31m1[m, Skipped: 0, Time elapsed: 4.892 s[1;31m <<< FAILURE![m - in com.saajf.manager.eewaapro.[1mClientRepositoryTest[m [[1;31mERROR[m] findByEmail Time elapsed: 0.239 s <<< ERROR! java.lang.NullPointerException: Cannot invoke "org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager.persist(Object)" because "com.saajf.manager.eewaapro.ClientRepositoryTest.entityManager" is null at com.saajf.manager.eewaapro.ClientRepositoryTest.findByEmail(ClientRepositoryTest.java:33)

2023-05-15 23:24:32.471 INFO 13068 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

times29

You need to autowire the TestEntityManager as follows:

@DataJpaTest
class ClientRepositoryTest {

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private TestEntityManager entityManager;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Getting NullPointerException while running a Cucumber test with Spring Boot, Selenium and JUnit

No tests were found - Empty test suite when running jUnit 5 testcase on bare-bone Spring Boot Maven project

Unsatisfied dependency when running a Junit Test in Spring app

Spring - Different test results when running from JUnit and Maven

Issue with @WithUserDetails and spring boot 1.4 TestEntityManager

Spring boot junit test - ClassNotFoundException

NullPointerException when running JUnit4 test, with MockitoHint "Unused..." and "args ok?"

no values persisted in database when running spring boot JPA test

Failed to load ApplicationContext when running Spring boot integration test

ClassNotFoundException on Spring JavaMailSenderImpl in JUnit test with Spring Boot

Spring boot unit test are not running

Running Spring boot test against Apache Camel Route with jUnit5

Spring Boot @Autowired in unit test returns NullPointerException

nullPointerException on sharedpreferences helper class When running a test

NullPointerException when running my test with page factory

spring-boot-starter-test with JUnit 5

How to make Junit test in spring boot

Spring Boot problem with JUnit execution test

Error creating bean in JUnit test in Spring Boot

Junit Test in Spring Boot does not inject the service

How to write Junit test case for spring boot:

Mockito Spring Boot - JUnit Test Case for Repository

No Such Method Error when Running JUnit Test

ClassNotFoundException when running a junit test in eclipse

Class Not Found Exception when running JUnit test

'Class not found' when running JUnit test

ClassNotFoundException when running JUnit test in Maven

Spring Boot - Junit unable to load configuration properties in junit test

@BeforeAll JUnit/spring-boot-test alternative that runs when application context starts