是否可以使用 Maven 的 test/resources 目录加载文件/资源@Value?
例如这样的东西:
@Value("${test/resources/path/to/file}") File file
Run Code Online (Sandbox Code Playgroud)
编辑:
我试过这个:
@Value("${someFile}") FileSystemResource file;
Run Code Online (Sandbox Code Playgroud)
但在运行时我看到它代表工作目录而不是测试/资源中的文件
我的 Springboot 应用程序工作正常,连接到数据源。对于 Junit,我通过排除 DatasourceAutoConfiguration、DataSourceTransactionManagerConfiguration、HibernateJpaAutoConfiguration 类来禁用数据源的自动配置,以避免 SpringBoot 自动配置数据源。
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.5.RELEASE</version>
<dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.2.jre8</version>
<dependency>
Run Code Online (Sandbox Code Playgroud)
主班
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"com.basepackage"})
public class SampleClass{
psvm(){
SpringApplication.run(SampleClass.class,args);
}
}
Run Code Online (Sandbox Code Playgroud)
Juni测试班
@RunWith(SpringRunner.class)
@SpringBootTest(classes=SampleClass.class)
@AutoConfigureMockMvc
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, DataSourceTransactionManagerConfiguration.class, HibernateJpaAutoConfiguration.class})
public class SampleControllerTest {
@MockBean
private SampleService service;
@Test
public void fetchUsers() {
Mockito.when(service.retrieveUsers().thenReturn(new SampleResponse());
}
Run Code Online (Sandbox Code Playgroud)
}
在 mvn 测试中,测试脚本已运行但失败,因为 Springboot 未自动配置 SampleRepository bean(可能是因为排除了 Datasource 和 HibernateJpa 自动配置类)
错误
Caused by UnsatisfiedDependencyException: Error creating bean with name ServiceDAOImpl, …Run Code Online (Sandbox Code Playgroud) 我想运行彼此完全隔离的 Spring Boot 集成测试(这是 Kent Beck 的单元测试想法)。因此,即使每个测试用例都有一个新的 h2 数据库。但我没有发现对此有任何帮助。仅:使用@Before等...但这不是一个好的解决方案。
这可能吗?如何?
当然:我不关心资源或时间效率。
Atm 我使用 junit 4.13 和 spring-boot-starter-test 2.2.6。
我有以下测试:
@SpringBootTest(classes = {SomeService.class, DtoMapperImpl.class})
class SomeServiceTest {
Run Code Online (Sandbox Code Playgroud)
以及以下映射器:
@Mapper(componentModel = "spring")
public interface DtoMapper {
EntityDto toDto(Entity entity);
}
Run Code Online (Sandbox Code Playgroud)
我不会更改包(这意味着DtoMapperImpl与DtoMapper位于同一包中)
一旦我将 Impl 更改为接口,我的测试就会失败:
@SpringBootTest(classes = {SomeService.class, DtoMapper.class})
class SomeServiceTest {
Run Code Online (Sandbox Code Playgroud)
引起:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“someService”的bean时出错:通过构造函数参数2表达的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“DtoMapper”类型的合格 bean:预计至少有 1 个符合自动装配候选资格的 bean。依赖注释:{}
您能建议解决这个问题的最佳方法吗?我正在使用 MapStruct 1.3.1.Final
我在运行 Azure DevOps Pipeline 时遇到问题。
我现在正在使用 Spring Boot Maven 项目。我想在不构建测试(src/test)文件的情况下运行构建管道,因为项目使用测试文件会构建失败,而没有测试文件则可以成功构建。
有什么设置或配置吗?非常感谢。
您可以查看图片以了解详细信息,谢谢。 请检查日志图像
maven spring-boot azure-devops spring-boot-test azure-devops-pipelines
我正在尝试将 testcontainers 与DockerComposeContainer. 我的 docker-compose.yaml 内容是这样的:
version: '3.8'
services:
postgresql:
image: postgres:13
environment:
POSTGRES_USER: ordering
POSTGRES_PASSWORD: ordering
POSTGRES_DB: ordering
Run Code Online (Sandbox Code Playgroud)
我使用以下 spring-boot 初始值设定项代码来声明容器:
static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
DockerComposeContainer<?> environment = new DockerComposeContainer<>(DOCKER_COMPOSE_FILE)
.withExposedService(DB_SERVICE_NAME, DB_PORT)
.withLocalCompose(true)
.start();
}
Run Code Online (Sandbox Code Playgroud)
这曾经一直有效,直到最近 MacOS 上的 docker-desktop 更新为止。
现在它抛出以下错误:
Caused by: org.testcontainers.containers.ContainerLaunchException: Aborting attempt to link to container l2whc7cxqkzd_postgresql_1 as it is not running
at org.testcontainers.containers.GenericContainer.applyConfiguration(GenericContainer.java:812)
at org.testcontainers.containers.GenericContainer.tryStart(GenericContainer.java:363)
... 40 more
Run Code Online (Sandbox Code Playgroud)
如果我在抛出异常之前在代码中放置一个断点并检查正在运行的 docker 容器,我会看到一个名为 name 的容器l2whc7cxqkzd-postgresql-1 …
我有一个简单的 Spring Boot (2.6.1) 测试,它抛出:
JdbcSQLIntegrityConstraintViolationException:
Unique index or primary key violation
Run Code Online (Sandbox Code Playgroud)
该测试从 加载数据test/resources/data.sql,其中只有一条语句:
INSERT INTO country (name) VALUES ('Italy');
Run Code Online (Sandbox Code Playgroud)
测试类是:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class FailingTest {
@Test
@Sql("/data.sql")
void test(){
assertTrue(true);
}
}
Run Code Online (Sandbox Code Playgroud)
域类是:
@Entity
public class Country {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@Column(nullable = false, unique = true)
private String name;
}
Run Code Online (Sandbox Code Playgroud)
该application.properties文件包含:
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.jpa.defer-datasource-initialization=true
Run Code Online (Sandbox Code Playgroud)
异常消息是:
org.springframework.jdbc.datasource.init.ScriptStatementFailedException:
Failed to execute SQL script statement #1 of class path resource [data.sql]:
INSERT …Run Code Online (Sandbox Code Playgroud) 我有一个 Spring Boot 应用程序 (1.5.10.RELEASE),其中包含一个主要的 (SpringBootApplication),如下所示:
@SpringBootApplication
@Configuration
@EntityScan(basePackages = { "db.modell", "db.modell.base" })
@ComponentScan(basePackages = { "de.gui.test" })
public class SpringBootConsoleApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
和两个 REST 控制器,如下所示:
@RestController
@RequestMapping("/as")
public class AController {
@Autowired
private ARepository aRepository;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Collection<A>> getAs() {
return new ResponseEntity<>(orgtFarbeRepository.findAll(), HttpStatus.OK);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<A> getA(@PathVariable long id) {
A a = ARepository.findOne(id);
if (party != null) …Run Code Online (Sandbox Code Playgroud) 给定一个类似的测试类:
@WebMvcTest
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyControllerTest {
... some tests
}
Run Code Online (Sandbox Code Playgroud)
我得到错误:
java.lang.IllegalStateException:配置错误:为测试类[com.example.MyControllerTest]找到了@BootstrapWith的多个声明:[@ org.springframework.test.context.BootstrapWith(value = class org.springframework.boot.test.autoconfigure .web.servlet.WebMvcTestContextBootstrapper),@ org.springframework.test.context.BootstrapWith(value = class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]
理想的目标是我只是在运行控制器测试,因此出于测试性能的原因,不想设置整个上下文-我只需要“ Web层”。
我可以删除该@SpringBootTest(properties = "spring.profiles.active=test")行-但是,现在我还没有激活测试配置文件,它可以通过属性以某种方式自定义Web上下文,例如将不再应用的杰克逊自定义。有没有一种方法可以只对“ Web层”进行测试并仍然激活弹簧轮廓?
我的环境是java version "10.0.2" 2018-07-17,spring boot1.5.16.RELEASE
spring-test spring-test-mvc spring-boot spring-web spring-boot-test
我不想加载整个Spring Boot配置来对我的DAO图层进行单元测试,因此创建了一个嵌套的配置类来抑制默认配置。但是,当我尝试指定要在测试之前运行的SQL脚本时,它找不到它们。
这是代码:
package com.test.customer.controller;
..
@RunWith(SpringRunner.class)
@JdbcTest
@Sql({"data.sql"})
public class InterviewInformationControllerTest {
@Configuration
static class TestConfiguration{
}
@Test
public void testCustomer() {
// code
}
}
I get the error: Cannot read SQL script from class path resource [com/test/customer/controller/data.sql]; nested exception is java.io.FileNotFoundException: class path resource [com/test/customer/controller/data.sql] cannot be opened because it does not exist
Run Code Online (Sandbox Code Playgroud)
我尝试将文件放置在src/main/resources(不喜欢)和src/test/resources(我喜欢)这两个位置
注意:我正在通过Eclipse在Eclipse中运行单元测试Run as -> JUnit test。
编辑:将static关键字添加到配置类
spring-boot-test ×10
spring-boot ×5
java ×3
junit ×2
maven ×2
spring ×2
azure-devops ×1
h2 ×1
hibernate ×1
mapstruct ×1
rest ×1
spring-test ×1
spring-web ×1
testing ×1
unit-testing ×1