使用JUnit 5的Spring @DataJpaTest [英] Spring @DataJpaTest with JUnit 5

查看:405
本文介绍了使用JUnit 5的Spring @DataJpaTest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎没有一种可以使@DataJpaTest正常运行的在线标准方法.

There doesn't seem to be a specific standard way I can find online that makes @DataJpaTest to run correctly.

是不是现在没有使用@DataJpaTest,并且所有测试都是使用@SpringBootTest在服务或控制器级别运行的?

Is it true that @DataJpaTest is not being used nowadays and all tests are run at the service or controller level using @SpringBootTest?

    @Repository
    public interface MyBeanRepository extends JpaRepository<MyBean, Long> { 
    }

    @Configuration
    @EnableJpaRepositories("com.app.repository.*")
    @ComponentScan(basePackages = { "com.app.repository.*" })
    public class ConfigurationRepository { 
    }


    @Entity
    public class MyBean {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "id")
        private Long id;

        @Version
        @Column(name = "version")
        private Integer version;

        @NotNull
        @Size(min = 2)
        private String name;
    }

    @DataJpaTest
    public class MyBeanIntegrationTest {

        @Autowired
        MyBeanRepository myBeanRepository;

        @Test
        public void testMarkerMethod() {
        }

        @Test
        public void testCount() {
            Assertions.assertNotNull(myBeanRepository , "Data on demand for 'MyBean' failed to initialize correctly");
        }
    }

使用Eclipse-> Run Junit运行会显示这些日志.

Running using the Eclipse->Run Junit shows these logs.

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
    at org.springframework.util.Assert.state(Assert.java:73)

使用gradle test运行会显示初始化失败的错误.

Running using gradle test shows the error that init failed.

FAILURE: Build failed with an exception.

* What went wrong:
Test failed.
    Failed tests:
        Test com.app.repository.MyBeanIntegrationTest#initializationError (Task: :test)

这是gradle脚本.

Here is the gradle script.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin")
    }
}

plugins {
    id 'org.springframework.boot' version '2.1.5.RELEASE'
    id 'java'
    id 'eclipse'

}

apply plugin: 'io.spring.dependency-management'

group = 'com.app'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenLocal()
    jcenter()
    mavenCentral()
}

test {
    useJUnitPlatform()
}

dependencies {
    // This dependency is exported to consumers, that is to say found on their compile classpath

    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    runtimeOnly 'org.hsqldb:hsqldb'
    testImplementation ('org.springframework.boot:spring-boot-starter-test') {
        // exlcuding junit 4
        exclude group: 'junit', module: 'junit'
    }

    /**
        Test Dependencies Follows
    **/


    // junit 5 api
    testCompile "org.junit.jupiter:junit-jupiter-api:5.2.0"
    // For junit5 parameterised test support
    testCompile "org.junit.jupiter:junit-jupiter-params:5.2.0"
    // junit 5 implementation
    testRuntime "org.junit.jupiter:junit-jupiter-engine:5.2.0"
    // Only required to run junit5 test from IDE
    testRuntime "org.junit.platform:junit-platform-launcher"

}

此问题已解决,并提交到同一存储库. https://github.com/john77eipe/spring-demo-1-test

This has been solved and committed at the same repository. https://github.com/john77eipe/spring-demo-1-test

推荐答案

添加Github链接是一个好主意.我在那里看到了以下问题:

It was a good idea to add a Github link. I can see following issues there:

1)如果您不能使用@SpringBootApplication注释主类,则可以使用:

1) If you can't have a main class annotated with @SpringBootApplication, you can use:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.app.repository")
public class MySampleApplication {
}

2)将ConfigurationRepository类的注释更改为:

2) Change annotations over your ConfigurationRepository class to:

@EnableJpaRepositories("com.app.repository")
@ComponentScan(basePackages = { "com.app.repository" })
public class ConfigurationRepository {

这应该让我们继续下一点:

That should let us proceed to the next point:

3)您的MyBeanIntegrationTest应该标注为:

3) Your MyBeanIntegrationTest should be annotated as:

@SpringBootTest(classes = MyAppApplication.class)
public class MyBeanIntegrationTest {

4)在application.yml中,您在最后一行有一个缩进的小问题.转换制表符,以便空格,应该没问题.

4) In application.yml you have a small issue with indentation in the last line. Convert tab so spaces and it should be fine.

5)接下来是MyBeanRepository界面.您不能在那里使用名为findOne的方法.事实是,在标记为JpaRepositoryCrudRepository等的接口中,方法名称需要遵循某些规则.如果您将其标记为包含MyBean类型的存储库,则应将方法名称更改为findById,因为Spring会在bean中查找名为id的属性.用findOne命名将导致测试失败,并显示以下信息:

5) Next thing is MyBeanRepository interface. You can't use a method named findOne there. Thing is, that in interfaces marked as JpaRepository or CrudRepository and so on, methods names need to follow certain rules. If you mark that it will be a repository containing type MyBean your method name should be changed to findById, because Spring will look for a property named id in your bean. Naming it by findOne will cause test to fail with:

No property findOne found for type MyBean!

修复这些问题后,您的测试将通过我的环境.

After fixing these things, your tests pass on my env.

我希望这会有所帮助!

这篇关于使用JUnit 5的Spring @DataJpaTest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆