Spring @DataJpaTest с помощью JUnit 5 - PullRequest
1 голос
/ 20 мая 2019

Кажется, что не существует определенного стандартного способа, которым я могу найти онлайн, который заставляет @DataJpaTest работать правильно.

Правда ли, что @DataJpaTest в настоящее время не используется, и все тесты выполняются на уровне службы или контроллера с использованием @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 показывает эти журналы.

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 показывает ошибку, которая не удалась init.

FAILURE: Build failed with an exception.

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

Вот скрипт gradle.

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"

}

EDIT:

Это было решено и зафиксировано в одном и том же хранилище. https://github.com/john77eipe/spring-demo-1-test

1 Ответ

0 голосов
/ 20 мая 2019

Хорошей идеей было добавить ссылку на Github.Я вижу следующие проблемы:

1) Если у вас нет основного класса, помеченного @SpringBootApplication, вы можете использовать:

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

2) Изменить аннотации над вашим ConfigurationRepository класс до:

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

Это должно позволить нам перейти к следующему пункту:

3) Ваш MyBeanIntegrationTest должен быть аннотирован как:

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

4) В application.yml у вас есть небольшая проблема с отступом в последней строке.Конвертируйте табуляцию так, чтобы она была пробелом, и все должно быть в порядке.

5) Следующим шагом является MyBeanRepository интерфейс.Вы не можете использовать метод с именем findOne там.Дело в том, что в интерфейсах, помеченных как JpaRepository или CrudRepository и т. Д., Имена методов должны следовать определенным правилам.Если вы отметите, что это будет репозиторий с типом MyBean, то имя вашего метода должно быть изменено на findById, потому что Spring будет искать свойство с именем id в вашем bean-компоненте.Присвоение ему имени findOne приведет к сбою теста:

No property findOne found for type MyBean!

После исправления этих ошибок ваши тесты пройдут по моей среде.

Надеюсь, это поможет!

...