Home > Mobile >  java.lang.NullPointerException: Cannot invoke "topjava.quest.service.DishService.getAll()"
java.lang.NullPointerException: Cannot invoke "topjava.quest.service.DishService.getAll()"

Time:08-02

For some reason, the service does not autowire.

In tests, can't use services it's throws exception java.lang.NullPointerException, example here:

public class DataJpaDishRepositoryTest extends AbstractServiceTest {

    @Autowired
    private DishService dishService;

    @Test
    public void getAllForRestaurant() {
        DISH_MATCHER.assertMatch(dishService.getAll(), dishList);
    }
}

class AbstractServiceTest:

@SpringJUnitConfig(locations = {
        "classpath:spring/spring-db.xml",
        "classpath:spring/spring-app.xml"})
@Sql(scripts = "classpath:db/populateDB.sql", config = @SqlConfig(encoding = "UTF-8"))
public class AbstractServiceTest {

    //  Check root cause in JUnit: https://github.com/junit-team/junit4/pull/778
    protected <T extends Throwable> void validateRootCause(Class<T> rootExceptionClass, Runnable runnable) {
        assertThrows(rootExceptionClass, () -> {
            try {
                runnable.run();
            } catch (Exception e) {
                throw ValidationUtil.getRootCause(e);
            }
        });
    }
}

Similarly with other services. I think that Spring doesn't works, why? In logs doesn't start AbstractTestContextBootstrapper. Below are the xml files.

<junit.version>4.13.2</junit.version> <spring-data-jpa.version>2.6.2</spring-data-jpa.version>

spring-db.xml, to shorten the code in stackoverflow.com, I removed xmlns:

    <jdbc:initialize-database data-source="dataSource" enabled="${database.init}">
        <jdbc:script location="${jdbc.initLocation}"/>
        <jdbc:script encoding="utf-8" location="classpath:db/populateDB.sql"/>
    </jdbc:initialize-database>

    <tx:annotation-driven/>

    <bean >
        <property name="staticMethod" value="org.slf4j.bridge.SLF4JBridgeHandler.install"/>
    </bean>

    <context:property-placeholder location="classpath:db/postgres.properties" system-properties-mode="OVERRIDE"/>

    <bean id="dataSource"
          
          p:driverClassName="org.postgresql.Driver"
          p:url="${database.url}"
          p:username="${database.username}"
          p:password="${database.password}"/>

    <bean id="entityManagerFactory" 
          p:dataSource-ref="dataSource"
          p:packagesToScan="topjava.quest.model">
        <property name="jpaPropertyMap">
            <map>
                <entry key="#{T(org.hibernate.cfg.AvailableSettings).FORMAT_SQL}" value="${hibernate.format_sql}"/>
                <entry key="#{T(org.hibernate.cfg.AvailableSettings).USE_SQL_COMMENTS}"
                       value="${hibernate.use_sql_comments}"/>
                <entry key="#{T(org.hibernate.cfg.AvailableSettings).JPA_PROXY_COMPLIANCE}"
                       value="${hibernate.jpa_proxy_compliance}"/>
                <!--https://github.com/hibernate/hibernate-orm/blob/master/documentation/src/main/asciidoc/userguide/chapters/caching/Caching.adoc#caching-provider-jcache-->
                <entry key="#{T(org.hibernate.cfg.AvailableSettings).CACHE_REGION_FACTORY}" value="org.hibernate.cache.jcache.internal.JCacheRegionFactory"/>
                <entry key="#{T(org.hibernate.cfg.AvailableSettings).USE_SECOND_LEVEL_CACHE}" value="true"/>
                <entry key="#{T(org.hibernate.cfg.AvailableSettings).USE_QUERY_CACHE}" value="false"/> <!--default-->
                <entry key="#{T(org.hibernate.cache.jcache.ConfigSettings).PROVIDER}" value="org.ehcache.jsr107.EhcacheCachingProvider"/>
            </map>
        </property>

        <property name="jpaVendorAdapter">
            <bean  p:showSql="${jpa.showSql}"/>
        </property>
    </bean>

    <bean id="transactionManager" 
          p:entityManagerFactory-ref="entityManagerFactory"/>

    <context:component-scan base-package="topjava.quest.repository.datajpa"/>
    <jpa:repositories base-package="topjava.quest.repository.datajpa"/>

spring-app.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="spring-cache.xml"/>
    <import resource="spring-security.xml"/>

    <context:component-scan base-package="topjava.quest.service"/>
</beans>

CodePudding user response:

Through torment, I found a solution. When switching to JUnit5 c JUnit4, did not delete in pom.xml old dependencies:

need delete:

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>${junit.version}</version>
   <scope>test</scope>
</dependency>

need add:

 <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
 </dependency>

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.8.2</version>
    <scope>test</scope>
</dependency>

and also need change import in classes:

import org.junit.jupiter.api.Test;
  • Related