【问题标题】:data.sql is not executed during unit test单元测试期间不执行 data.sql
【发布时间】:2021-10-17 12:35:25
【问题描述】:

我正在为基本的 CRUD API 实施单元测试。我有一个名为 Classified 的类,其中包含一个名为 Category 的类的实例。他们都有自己的数据库。为了初始化类别数据库,我在资源文件夹下创建了一个“data.sql”文件。它在正常执行期间工作得很好,但在我运行测试时它没有被执行。我正在使用 h2 内存数据库。

data.sql 内容:

insert into CATEGORY values (1, 'Real Estate');
insert into CATEGORY values (2, 'Vehicle');
insert into CATEGORY values (3, 'Shopping');
insert into CATEGORY values (4, 'Other');

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
public class ClassifiedServiceTest {
@Mock
private ClassifiedRepository classifiedRepository;
@Mock
private ClassifiedHistoryRepository classifiedHistoryRepository;
@Mock
private CategoryRepository categoryRepository;
@InjectMocks
private ClassifiedService classifiedService;

@Test
public void createClassifiedTest() throws FileNotFoundException {
    // This method throws an exception related to CATEGORY table being empty
    }
}

我尝试将 @Sql("data.sql") 添加到测试类,但后来我得到了

org.springframework.test.context.transaction.TestContextTransactionUtils - Caught exception while retrieving DataSource for test context [DefaultTestContext@1189dd52 testClass = ClassifiedServiceTest, testInstance = com.sahibinden.codecase.services.ClassifiedServiceTest@1133ec6e, testMethod = createAndDeactivateClassifiedTest@ClassifiedServiceTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@36bc55de testClass = ClassifiedServiceTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@a4102b8, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@7a52f2a2, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@75f32542, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@229d10bd], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false, 'org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.mocks' -> org.mockito.internal.configuration.InjectingAnnotationEngine$$Lambda$113/0x0000000800da41d8@355e34c7]]
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' 
available

如何在运行这些测试之前配置我的测试类以运行 data.sql 并填充数据库

【问题讨论】:

    标签: java spring-boot unit-testing h2


    【解决方案1】:

    就像 Farid 所说,您不能在单元测试中使用 Spring 数据,而是在集成测试中使用

    @SpringBootTest

    用于挂载 SpringBoot 上下文

    【讨论】:

      【解决方案2】:

      为此,您应该使用@SpringBootTest 让 Spring Boot 使用 H2 自动配置您的嵌入式数据源。 然后 Spring Boot 将执行您的 schema.sqldata.sql 以自动设置您的 H2 数据库。 如果您使用@SpringBootTest,则必须使用@Autowired 而不是@InjectMocks 注入您的bean,并且您不需要模拟其他bean。

      @SpringBootTest
      public class ClassifiedServiceTest {
      
      @Autowired
      private ClassifiedService classifiedService;
      
      @Test
      public void createClassifiedTest() throws FileNotFoundException {
          // This method throws an exception related to CATEGORY table being empty
          }
      }
      

      如果您的 Spring Boot 应用启动时间过长,您也可以使用切片测试。为此,您可以这样做:

      @DataJpaTest
      @Import(ClassifiedServiceImpl.class) // You need the implementation here 
      public class ClassifiedServiceTest {
      
      @Autowired
      private ClassifiedService classifiedService;
      
      @Test
      public void createClassifiedTest() throws FileNotFoundException {
          // This method throws an exception related to CATEGORY table being empty
          }
      }
      
      

      它只会设置使用 JPA 所需的所有内容并在应用程序上下文中加载您的 ClassifiedService

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-10
        • 2019-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-21
        • 1970-01-01
        • 2017-06-08
        相关资源
        最近更新 更多