Интеграционный тест Springboot @DataJpaTest с внешней базой данных sql server

#sql-server #spring-boot #spring-data-jpa #integration-testing #junit5

Вопрос:

У меня есть класс репозитория ниже в моем проекте spring boot. В этом репозитории есть метод, который возвращает данные инвентаризации с SQL-сервера. Это работа над моим проектом.

 @Repository
public interface InventoryRepository extends JpaRepository<Inventory, Integer> {
  Inventory findByInventoryIdAndCompanyId(Integer inventoryId, Integer companyId);        
}
 

Я хочу написать интеграцию для репозитория, которая должна получать данные из базы данных SQL server среды разработки и тестирования.
В этой базе данных среды разработки и тестирования уже есть данные.
Ниже приведены приложения.файлы yml в папке «Мои ресурсы» (я намеренно изменил URL — адрес и учетные данные, чтобы показать их здесь).

приложение.yml :

 spring:
  profiles.active: development
 

разработка приложений.yml :

 spring:
  profiles: development

spring.datasource.type: com.zaxxer.hikari.HikariDataSource
spring.datasource.jdbc-url: jdbc:sqlserver://22.22.22.22:1533;instanceName=SQLSVR;databaseName=dev
spring.datasource.username: admin
spring.datasource.password: admin
spring.datasource.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
 

приложение-тест.yml :

 spring:
  profiles: test

spring.datasource.type: com.zaxxer.hikari.HikariDataSource
spring.datasource.jdbc-url: jdbc:sqlserver://11.11.11.11:1533;instanceName=SQLSVR;databaseName=qa
spring.datasource.url: jdbc:sqlserver://11.11.11.11:1533;instanceName=SQLSVR;databaseName=qa
spring.datasource.username: admin
spring.datasource.password: admin
spring.datasource.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
 

Ниже приведен тестовый класс для моего репозитория.

 @ExtendWith(SpringExtension.class)
@DataJpaTest
@ContextConfiguration
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class InventoryRepositoryTest {

    @Autowired
    InventoryRepository inventoryRepository;

    @Test
    public void getRepositoryByIdTest () {
        Assertions.assertEquals(1,inventoryRepository.findByInventoryIdAndCompanyId(1,1));
    }
}
 

Ниже приведена ошибка, которую я получаю при выполнении этого теста

 2021-10-18 03:35:38.917  INFO 11968 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@18d87d80 testClass = InventoryRepositoryTest, testInstance = com.cropin.mwarehouse.common.repository.InventoryRepositoryTest@437da279, testMethod = getRepositoryByIdTest@InventoryRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@618425b5 testClass = InventoryRepositoryTest, locations = '{}', classes = '{class com.cropin.mwarehouse.CropinMWarehouseServiceApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@58695725 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4b2bac3f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@26794848, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@6ad82709, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@fb6c1252, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@158a8276], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@f310675]; rollback [true]
2021-10-18 03:35:38.963 DEBUG 11968 --- [           main] org.hibernate.SQL                        : 
    select
        inventory0_.inventoryId as inventor1_10_,
        inventory0_.createdBy as createdB2_10_,
        inventory0_.createdDate as createdD3_10_,
        inventory0_.lastModifiedBy as lastModi4_10_,
        inventory0_.lastModifiedDate as lastModi5_10_,
        inventory0_.balanceWeight as balanceW6_10_,
        inventory0_.batchCreationDate as batchCre7_10_,
        inventory0_.batchNumber as batchNum8_10_,
        inventory0_.clientId as clientId9_10_,
        inventory0_.companyId as company10_10_,
        inventory0_.currencyUnitId as currenc11_10_,
        inventory0_.dateOfEntry as dateOfE12_10_,
        inventory0_.harvestReferenceId as harvest13_10_,
        inventory0_.inventoryStatus as invento14_10_,
        inventory0_.isActive as isActiv15_10_,
        inventory0_.itemId as itemId16_10_,
        inventory0_.locationId as locatio17_10_,
        inventory0_.parentInventoryId as parentI18_10_,
        inventory0_.processId as process19_10_,
        inventory0_.quantity as quantit20_10_,
        inventory0_.quantityBalance as quantit21_10_,
        inventory0_.supplierId as supplie22_10_,
        inventory0_.unitPrice as unitPri23_10_,
        inventory0_.weight as weight24_10_ 
    from
        inv.Inventory inventory0_ 
    where
        inventory0_.inventoryId=? 
        and inventory0_.companyId=?
Hibernate: 
    select
        inventory0_.inventoryId as inventor1_10_,
        inventory0_.createdBy as createdB2_10_,
        inventory0_.createdDate as createdD3_10_,
        inventory0_.lastModifiedBy as lastModi4_10_,
        inventory0_.lastModifiedDate as lastModi5_10_,
        inventory0_.balanceWeight as balanceW6_10_,
        inventory0_.batchCreationDate as batchCre7_10_,
        inventory0_.batchNumber as batchNum8_10_,
        inventory0_.clientId as clientId9_10_,
        inventory0_.companyId as company10_10_,
        inventory0_.currencyUnitId as currenc11_10_,
        inventory0_.dateOfEntry as dateOfE12_10_,
        inventory0_.harvestReferenceId as harvest13_10_,
        inventory0_.inventoryStatus as invento14_10_,
        inventory0_.isActive as isActiv15_10_,
        inventory0_.itemId as itemId16_10_,
        inventory0_.locationId as locatio17_10_,
        inventory0_.parentInventoryId as parentI18_10_,
        inventory0_.processId as process19_10_,
        inventory0_.quantity as quantit20_10_,
        inventory0_.quantityBalance as quantit21_10_,
        inventory0_.supplierId as supplie22_10_,
        inventory0_.unitPrice as unitPri23_10_,
        inventory0_.weight as weight24_10_ 
    from
        inv.Inventory inventory0_ 
    where
        inventory0_.inventoryId=? 
        and inventory0_.companyId=?
2021-10-18 03:35:39.142 DEBUG 11968 --- [           main] org.hibernate.SQL                        : 
    select
        companymas0_.companyId as companyI1_1_0_,
        companymas0_.createdBy as createdB2_1_0_,
        companymas0_.createdDate as createdD3_1_0_,
        companymas0_.lastModifiedBy as lastModi4_1_0_,
        companymas0_.lastModifiedDate as lastModi5_1_0_,
        companymas0_.companyAddress as companyA6_1_0_,
        companymas0_.companyCode as companyC7_1_0_,
        companymas0_.companyDesc as companyD8_1_0_,
        companymas0_.companyLogo as companyL9_1_0_,
        companymas0_.companyName as company10_1_0_,
        companymas0_.companyPreferredSubDomain as company11_1_0_,
        companymas0_.contactEmail as contact12_1_0_,
        companymas0_.contactNumber as contact13_1_0_,
        companymas0_.defaultRadiusForGeoFencing as default14_1_0_,
        companymas0_.fiscalMonth as fiscalM15_1_0_,
        companymas0_.isGDPRRequired as isGDPRR16_1_0_,
        companymas0_.isActive as isActiv17_1_0_,
        companymas0_.isBlueToothRequired as isBlueT18_1_0_,
        companymas0_.isGeoFencingRequired as isGeoFe19_1_0_,
        companymas0_.isHarvestPaid as isHarve20_1_0_,
        companymas0_.isShareImage as isShare21_1_0_,
        companymas0_.isVerified as isVerif22_1_0_,
        companymas0_.isZohoEnable as isZohoE23_1_0_,
        companymas0_.planTypeId as planTyp24_1_0_,
        companymas0_.primaryCountry as primary25_1_0_,
        companymas0_.sTA as sTA26_1_0_,
        companymas0_.webSite as webSite27_1_0_ 
    from
        dbo.CompanyMaster companymas0_ 
    where
        companymas0_.companyId=?
Hibernate: 
    select
        companymas0_.companyId as companyI1_1_0_,
        companymas0_.createdBy as createdB2_1_0_,
        companymas0_.createdDate as createdD3_1_0_,
        companymas0_.lastModifiedBy as lastModi4_1_0_,
        companymas0_.lastModifiedDate as lastModi5_1_0_,
        companymas0_.companyAddress as companyA6_1_0_,
        companymas0_.companyCode as companyC7_1_0_,
        companymas0_.companyDesc as companyD8_1_0_,
        companymas0_.companyLogo as companyL9_1_0_,
        companymas0_.companyName as company10_1_0_,
        companymas0_.companyPreferredSubDomain as company11_1_0_,
        companymas0_.contactEmail as contact12_1_0_,
        companymas0_.contactNumber as contact13_1_0_,
        companymas0_.defaultRadiusForGeoFencing as default14_1_0_,
        companymas0_.fiscalMonth as fiscalM15_1_0_,
        companymas0_.isGDPRRequired as isGDPRR16_1_0_,
        companymas0_.isActive as isActiv17_1_0_,
        companymas0_.isBlueToothRequired as isBlueT18_1_0_,
        companymas0_.isGeoFencingRequired as isGeoFe19_1_0_,
        companymas0_.isHarvestPaid as isHarve20_1_0_,
        companymas0_.isShareImage as isShare21_1_0_,
        companymas0_.isVerified as isVerif22_1_0_,
        companymas0_.isZohoEnable as isZohoE23_1_0_,
        companymas0_.planTypeId as planTyp24_1_0_,
        companymas0_.primaryCountry as primary25_1_0_,
        companymas0_.sTA as sTA26_1_0_,
        companymas0_.webSite as webSite27_1_0_ 
    from
        dbo.CompanyMaster companymas0_ 
    where
        companymas0_.companyId=?
2021-10-18 03:35:39.292 DEBUG 11968 --- [           main] org.hibernate.SQL                        : 
    select
        locationma0_.locationId as location1_22_0_,
        locationma0_.createdBy as createdB2_22_0_,
        locationma0_.createdDate as createdD3_22_0_,
        locationma0_.lastModifiedBy as lastModi4_22_0_,
        locationma0_.lastModifiedDate as lastModi5_22_0_,
        locationma0_.addressLine1 as addressL6_22_0_,
        locationma0_.addressLine2 as addressL7_22_0_,
        locationma0_.companyId as companyI8_22_0_,
        locationma0_.coordinates as coordina9_22_0_,
        locationma0_.districtId as distric10_22_0_,
        locationma0_.geoId as geoId11_22_0_,
        locationma0_.imageName as imageNa12_22_0_,
        locationma0_.isActive as isActiv13_22_0_,
        locationma0_.latitude as latitud14_22_0_,
        locationma0_.locationTypeId as locatio15_22_0_,
        locationma0_.longitude as longitu16_22_0_,
        locationma0_.name as name17_22_0_,
        locationma0_.parentLocationId as parentL18_22_0_,
        locationma0_.pincode as pincode19_22_0_,
        locationma0_.placeName as placeNa20_22_0_,
        locationma0_.stateId as stateId21_22_0_ 
    from
        inv.LocationMaster locationma0_ 
    where
        locationma0_.locationId=?
Hibernate: 
    select
        locationma0_.locationId as location1_22_0_,
        locationma0_.createdBy as createdB2_22_0_,
        locationma0_.createdDate as createdD3_22_0_,
        locationma0_.lastModifiedBy as lastModi4_22_0_,
        locationma0_.lastModifiedDate as lastModi5_22_0_,
        locationma0_.addressLine1 as addressL6_22_0_,
        locationma0_.addressLine2 as addressL7_22_0_,
        locationma0_.companyId as companyI8_22_0_,
        locationma0_.coordinates as coordina9_22_0_,
        locationma0_.districtId as distric10_22_0_,
        locationma0_.geoId as geoId11_22_0_,
        locationma0_.imageName as imageNa12_22_0_,
        locationma0_.isActive as isActiv13_22_0_,
        locationma0_.latitude as latitud14_22_0_,
        locationma0_.locationTypeId as locatio15_22_0_,
        locationma0_.longitude as longitu16_22_0_,
        locationma0_.name as name17_22_0_,
        locationma0_.parentLocationId as parentL18_22_0_,
        locationma0_.pincode as pincode19_22_0_,
        locationma0_.placeName as placeNa20_22_0_,
        locationma0_.stateId as stateId21_22_0_ 
    from
        inv.LocationMaster locationma0_ 
    where
        locationma0_.locationId=?
2021-10-18 03:35:39.663  INFO 11968 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@18d87d80 testClass = InventoryRepositoryTest, testInstance = com.cropin.mwarehouse.common.repository.InventoryRepositoryTest@437da279, testMethod = getRepositoryByIdTest@InventoryRepositoryTest, testException = org.opentest4j.AssertionFailedError: expected: <1> but was: <com.cropin.mwarehouse.common.entity.Inventory@5b58f639>, mergedContextConfiguration = [MergedContextConfiguration@618425b5 testClass = InventoryRepositoryTest, locations = '{}', classes = '{class com.cropin.mwarehouse.CropinMWarehouseServiceApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@58695725 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4b2bac3f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@26794848, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@6ad82709, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@fb6c1252, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@158a8276], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]

org.opentest4j.AssertionFailedError: 
Expected :1
Actual   :com.cropin.mwarehouse.common.entity.Inventory@5b58f639
<Click to see difference>


    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
    at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
    at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
    at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
    at com.cropin.mwarehouse.common.repository.InventoryRepositoryTest.getRepositoryByIdTest(InventoryRepositoryTest.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
 

Ниже приведены вопросы, на которые я ищу ответы:

  1. Работает ли @DataJpaTest только с базой данных в памяти? Здесь я пытаюсь подключиться к внешней базе данных sql server, действительно ли она подключается к ней?
  2. Если @DataJpaTest может подключаться к внешней базе данных sql server, то почему это не удается, так как у меня уже есть записи, доступные для указанного выше параметра теста. 3.Как я могу использовать профилирование здесь? Существует вариант @ActiveProfile, но я хочу использовать один и тот же блок тестирования как для разработки среды, так и для контроля качества, в этом случае как будет работать это профилирование? 4.In журнал ошибок показывает активный профиль как пустой, что это значит? Разве это не подбор профиля развития?
  3. Как я могу выполнить тест интеграции, подключившись к своей БД разработки и контроля качества, в которой уже есть данные. Я не хочу использовать в БД памяти.

Пожалуйста, помогите мне с этим вопросом.

Ответ №1:

Фактическое соединение, похоже, работает. @DataJpaTest работает с любой DataSource конфигурацией, просто требуется самоуверенный подход к использованию базы данных в памяти. Вы уже добавили необходимый код для отказа и используете свой собственный DataSource с:

 @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
 

Фактический сбой теста происходит из-за того, что вы пытаетесь сравнить an int с реальным объектом Java. Либо верните все объекты и проверьте размер:

 Assertions.assertEquals(1, inventoryRepository.findAll().size());
 

… или утверждать, что результат не равен нулю:

 Assertions.assertNotNull(inventoryRepository.findByInventoryIdAndCompanyId(1,1));
 

Более внимательно посмотрите на ошибку утверждения:

 org.opentest4j.AssertionFailedError: 
Expected :1
Actual   :com.cropin.mwarehouse.common.entity.Inventory@5b58f639
<Click to see difference>
 

К вашему сведению: вы должны иметь возможность уменьшить настройку теста до:

 // @ExtendWith(SpringExtension.class) already comes with @DataJpaTest
@DataJpaTest
// @ContextConfiguration
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class InventoryRepositoryTest {