【发布时间】: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