Springboot @DataJpaTest 与外部 sql server db 集成测试

Posted

技术标签:

【中文标题】Springboot @DataJpaTest 与外部 sql server db 集成测试【英文标题】:Springboot @DataJpaTest Integration test with external sql server db 【发布时间】:2021-12-05 02:12:49 【问题描述】:

我的 Spring Boot 项目中有以下存储库类。此存储库有一个从 SQL 服务器返回库存数据的方法。这是我的项目。

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

我想为应该从开发和测试环境 SQL 服务器数据库获取数据的存储库编写一个集成。 这个开发和测试环境数据库已经有数据了。 以下是我的资源文件夹中的 application.yml 文件(我已故意更改了 url 和凭据以在此处显示)。

application.yml:

spring:
  profiles.active: development

application-developement.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

application-test.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)

以下是我正在寻找答案的问题:

    @DataJpaTest 是否仅适用于内存数据库?这里我正在尝试连接外部 sql server db 是否真的连接到它? 如果@DataJpaTest 能够连接到外部 sql 服务器数据库,那么为什么它会失败,因为我已经有可用于上述测试参数的记录。 3.如何在这里使用分析? @ActiveProfile 有一个选项,但我想对环境 dev 和 qa 使用相同的测试块,因为这个分析将如何工作? 4.在错误日志中显示活动配置文件为空,这是什么意思?是不是在获取开发配置文件? 如何实现连接到我的 dev 和 qa db 的集成测试,这些数据库已经有数据了。我不想在内存数据库中使用。

请帮我解答这个问题。

【问题讨论】:

【参考方案1】:

实际连接似乎有效。 @DataJpaTest 适用于任何 DataSource 配置,它只是采用固执己见的方法来使用内存数据库。您已经添加了选择退出所需的代码并使用您自己的DataSource

@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)

实际测试失败是因为您尝试将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 

【讨论】:

以上是关于Springboot @DataJpaTest 与外部 sql server db 集成测试的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 1.4 @DataJpaTest - 创建名为“dataSource”的 bean 时出错

Spring Boot:使用 @DataJpaTest 和 Flyway 设置 Hibernate 命名策略

使用 @DataJpaTest 设置自定义方案

如何在使用 DataJpaTest 的 Spring Boot 2.0 测试中访问 H2 控制台

使用 Eureka / Feign 时 @DataJpaTest 失败

如何在 SpringBootTest 中的 @DataJpaTest 中导入配置类?