Testing Spring JPA Repositories (non Spring Boot)

2019-09-21 14:54发布

All the resources I can find online related to this topic are on Spring Boot. Sadly I am working on a classic Spring MVC project based on Spring 4.1.

My Spring Context is in the dispatcher servlet and the data source definitions are integrated in the hibernate sessionFactory bean.

The Entity class I need tested:

@Entity
@Table(name = "pos_user")
public class POSUser {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "id")
    @MapsId
    private UserInf userInf;

    private String pin;

    @Column(name = "created_by")
    private int createdBy;

    @Column(name = "created_at")
    private Timestamp createdAt;

    @Column(name = "updated_by")
    private int updatedBy;

    @Column(name = "updated_at")
    private Timestamp updatedAt;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public UserInf getUserInf() {
        return userInf;
    }

    public void setUserInf(UserInf userInf) {
        this.userInf = userInf;
    }

    public String getPin() {
        return pin;
    }

    public void setPin(String pin) {
        this.pin = pin;
    }

    public int getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(int createdBy) {
        this.createdBy = createdBy;
    }

    public Timestamp getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Timestamp createdAt) {
        this.createdAt = createdAt;
    }

    public int getUpdatedBy() {
        return updatedBy;
    }

    public void setUpdatedBy(int updatedBy) {
        this.updatedBy = updatedBy;
    }

    public Timestamp getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Timestamp updatedAt) {
        this.updatedAt = updatedAt;
    }
}

The repository class:

@Repository
public class POSUserDao extends BaseDao {

    public POSUser getByAuthCredential(AuthCredential user) {
        try (Session session = this.sessionFactory.openSession()) {
            return session.createQuery("FROM POSUser AS usr WHERE usr.usrInf.id = :id", POSUser.class).setParameter("id", user.getId()).setMaxResults(1).getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

My current test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:WEB-INF/dispatcher-servlet.xml"})
@WebAppConfiguration
public class POSUserDaoTest {

    private AuthCredential authCredential;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    AuthCredentialDao authCredentialDao;

    @Autowired
    POSUserDao posUserDao;

    @Before
    public void setUp() throws Exception {
       this.authCredential = authCredentialDao.getById(1);
    }

    @Test
    public void testGetByAuthCredential() {
    POSUser user = posUserDao.getByAuthCredential(this.authCredential);

       assertNotNull(user);
    }
}

But when running this as a JUnit test I get a "Could not load TestContextBootstrapper[null]. Specify @BootstrapWith's 'value' attribute or make the default bootstrapper class available". I want to use my default application context for testing and use my development database for the data data layer tests.

The complete exception:

java.lang.IllegalStateException: Could not load TestContextBootstrapper [null]. Specify @BootstrapWith's 'value' attribute or make the default bootstrapper class available.
    at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:143)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:87)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:73)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:522)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/util/Set;
    at org.springframework.test.context.BootstrapUtils.resolveExplicitTestContextBootstrapper(BootstrapUtils.java:150)
    at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:126)
    ... 20 more

Update:

I have used Maven Dependency plugin to get the following list of used dependencies and it seems spring-test version 4.3 is being used with spring-core 4.1.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building Cineops Admin 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:3.0.0:tree (default-cli) @ admin ---
[INFO] Verbose not supported since maven-dependency-plugin 3.0
[INFO] 
[INFO] >>> maven-dependency-plugin:3.0.0:analyze (default-cli) > test-compile @ admin >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ admin ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/saminda/git/CineOps/CineOps/CineOps Web/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ admin ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ admin ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 322 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ admin ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] <<< maven-dependency-plugin:3.0.0:analyze (default-cli) < test-compile @ admin <<<
[INFO] 
[INFO] --- maven-dependency-plugin:3.0.0:analyze (default-cli) @ admin ---
[INFO] Used declared dependencies found:
[INFO]    javax:javaee-web-api:jar:7.0:provided
[INFO]    org.springframework:spring-web:jar:4.1.4.RELEASE:compile
[INFO]    org.springframework:spring-webmvc:jar:4.1.4.RELEASE:compile
[INFO]    org.hibernate:hibernate-core:jar:5.2.5.Final:compile
[INFO]    com.fasterxml.jackson.core:jackson-core:jar:2.7.5:compile
[INFO]    com.fasterxml.jackson.core:jackson-databind:jar:2.7.5:compile
[INFO]    org.springframework.security:spring-security-core:jar:3.2.1.RELEASE:compile
[INFO]    org.springframework.security:spring-security-web:jar:3.2.1.RELEASE:compile
[INFO]    org.springframework.security.oauth:spring-security-oauth2:jar:1.0.5.RELEASE:compile
[INFO]    org.apache.velocity:velocity:jar:1.7:compile
[INFO]    org.hibernate:hibernate-validator:jar:5.0.1.Final:compile
[INFO]    joda-time:joda-time:jar:2.9.4:compile
[INFO]    javax.mail:mail:jar:1.4.4:compile
[INFO]    commons-validator:commons-validator:jar:1.4.0:compile
[INFO]    com.itextpdf:itextpdf:jar:5.5.10:compile
[INFO]    com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:jar:2.8.6:compile
[INFO]    org.springframework:spring-test:jar:4.3.0.RELEASE:test
[INFO]    junit:junit:jar:4.12:compile
[WARNING] Used undeclared dependencies found:
[WARNING]    org.springframework:spring-core:jar:4.1.4.RELEASE:compile
[WARNING]    org.springframework:spring-context:jar:4.1.4.RELEASE:compile
[WARNING]    com.fasterxml.jackson.core:jackson-annotations:jar:2.7.0:compile
[WARNING]    commons-logging:commons-logging:jar:1.1.1:compile
[WARNING]    org.springframework:spring-beans:jar:4.1.4.RELEASE:compile
[WARNING]    commons-lang:commons-lang:jar:2.4:compile
[WARNING] Unused declared dependencies found:
[WARNING]    org.springframework:spring-orm:jar:4.1.4.RELEASE:compile
[WARNING]    javax.servlet:javax.servlet-api:jar:3.1.0:compile
[WARNING]    com.itextpdf:itext-pdfa:jar:5.5.10:compile
[WARNING]    org.mockito:mockito-all:jar:1.9.5:compile
[WARNING]    com.itextpdf.tool:xmlworker:jar:5.5.10:compile
[WARNING]    mysql:mysql-connector-java:jar:5.1.6:compile
[WARNING]    commons-fileupload:commons-fileupload:jar:1.3.1:compile
[WARNING]    com.itextpdf:itext-xtra:jar:5.5.10:compile
[WARNING]    org.springframework.security:spring-security-crypto:jar:3.2.1.RELEASE:compile
[WARNING]    javax.validation:validation-api:jar:1.1.0.Final:compile
[WARNING]    javax.servlet:jstl:jar:1.2:compile
[WARNING]    org.springframework.security:spring-security-config:jar:3.2.1.RELEASE:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.509 s
[INFO] Finished at: 2018-01-17T18:57:03+05:30
[INFO] Final Memory: 22M/353M
[INFO] ------------------------------------------------------------------------

Result of dependancy-tree:

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building Cineops Admin 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:3.0.0:tree (default-cli) @ admin ---
[INFO] com.cineops:admin:war:1.0-SNAPSHOT
[INFO] +- javax:javaee-web-api:jar:7.0:provided
[INFO] +- commons-fileupload:commons-fileupload:jar:1.3.1:compile
[INFO] |  \- commons-io:commons-io:jar:2.2:compile
[INFO] +- org.springframework:spring-web:jar:4.1.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-aop:jar:4.1.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.1.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:4.1.4.RELEASE:compile
[INFO] |  \- org.springframework:spring-core:jar:4.1.4.RELEASE:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.1.4.RELEASE:compile
[INFO] |  \- org.springframework:spring-expression:jar:4.1.4.RELEASE:compile
[INFO] +- org.springframework:spring-orm:jar:4.1.4.RELEASE:compile
[INFO] |  +- org.springframework:spring-jdbc:jar:4.1.4.RELEASE:compile
[INFO] |  \- org.springframework:spring-tx:jar:4.1.4.RELEASE:compile
[INFO] +- org.hibernate:hibernate-core:jar:5.2.5.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  +- org.javassist:javassist:jar:3.20.0-GA:compile
[INFO] |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  +- org.apache.geronimo.specs:geronimo-jta_1.1_spec:jar:1.1.1:compile
[INFO] |  +- org.jboss:jandex:jar:2.0.3.Final:compile
[INFO] |  +- com.fasterxml:classmate:jar:1.3.0:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  +- org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final:compile
[INFO] |  \- javax.enterprise:cdi-api:jar:1.1:compile
[INFO] |     +- javax.el:el-api:jar:2.2:compile
[INFO] |     +- org.jboss.spec.javax.interceptor:jboss-interceptors-api_1.1_spec:jar:1.0.0.Beta1:compile
[INFO] |     +- javax.annotation:jsr250-api:jar:1.0:compile
[INFO] |     \- javax.inject:javax.inject:jar:1:compile
[INFO] +- com.fasterxml.jackson.core:jackson-core:jar:2.7.5:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.7.5:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-annotations:jar:2.7.0:compile
[INFO] +- mysql:mysql-connector-java:jar:5.1.6:compile
[INFO] +- org.springframework.security:spring-security-core:jar:3.2.1.RELEASE:compile
[INFO] |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] +- org.springframework.security:spring-security-web:jar:3.2.1.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-config:jar:3.2.1.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-crypto:jar:3.2.1.RELEASE:compile
[INFO] +- org.springframework.security.oauth:spring-security-oauth2:jar:1.0.5.RELEASE:compile
[INFO] |  +- commons-codec:commons-codec:jar:1.3:compile
[INFO] |  \- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.2:compile
[INFO] |     \- org.codehaus.jackson:jackson-core-asl:jar:1.9.2:compile
[INFO] +- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] +- javax.servlet:jstl:jar:1.2:compile
[INFO] +- org.apache.velocity:velocity:jar:1.7:compile
[INFO] |  +- commons-collections:commons-collections:jar:3.2.1:compile
[INFO] |  \- commons-lang:commons-lang:jar:2.4:compile
[INFO] +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] +- org.hibernate:hibernate-validator:jar:5.0.1.Final:compile
[INFO] +- joda-time:joda-time:jar:2.9.4:compile
[INFO] +- javax.mail:mail:jar:1.4.4:compile
[INFO] |  \- javax.activation:activation:jar:1.1:compile
[INFO] +- commons-validator:commons-validator:jar:1.4.0:compile
[INFO] |  +- commons-beanutils:commons-beanutils:jar:1.8.3:compile
[INFO] |  +- commons-digester:commons-digester:jar:1.8:compile
[INFO] |  \- commons-logging:commons-logging:jar:1.1.1:compile
[INFO] +- com.itextpdf:itextpdf:jar:5.5.10:compile
[INFO] +- com.itextpdf:itext-pdfa:jar:5.5.10:compile
[INFO] +- com.itextpdf:itext-xtra:jar:5.5.10:compile
[INFO] |  \- org.apache.commons:commons-imaging:jar:1.0-SNAPSHOT:compile
[INFO] +- com.itextpdf.tool:xmlworker:jar:5.5.10:compile
[INFO] +- com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:jar:2.8.6:compile
[INFO] |  \- javax.transaction:jta:jar:1.1:compile
[INFO] +- org.mockito:mockito-all:jar:1.9.5:compile
[INFO] +- org.springframework:spring-test:jar:4.1.4.RELEASE:test
[INFO] \- junit:junit:jar:4.12:compile
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.954 s
[INFO] Finished at: 2018-01-17T19:15:56+05:30
[INFO] Final Memory: 15M/217M
[INFO] ------------------------------------------------------------------------

Update 2:

I updated spring to version 4.3 and it seems this was an issue with conflicting dependencies. I still got a "Application Context not found" issue and I will try to address that.

1条回答
Fickle 薄情
2楼-- · 2019-09-21 15:30

This

java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/util/Set;

sounds like a version conflict.

Make sure the versions of any Spring related test modules you include match/are compatible with the version of Spring you are using.

Use mavens dependency plugin or the equivalent of your build tool of choice to see and fix any conflicts.

查看更多
登录 后发表回答