简体   繁体   English

Junit 5 带测试应用程序.properties

[英]Junit 5 with test application.properties

I am learning Junit 5 and test cases.我正在学习 Junit 5 和测试用例。 I am using spring boot version '2.2.6.RELEASE and JUnit 5, in my application, I have a method that processes based on the boolean flag from property file.我正在使用 spring 引导版本 '2.2.6.RELEASE 和 JUnit 5,在我的应用程序中,我有一个基于文件中的 Z84E2C64F38F78BA3EA5C905AB5A2DA2 标志的方法。

\src\main\resources\application.properties \src\main\resources\application.properties

#data base connection properties
spring.app.datasource.url=jdbc:mysql://localhost:3306/student_db
spring.app.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.app.datasource.username=root
spring.datasource.password=root
spring.app.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

#additional properties
spring.property.name=shrikant
spring.property.enable=false

database connection properties are used to create the database connection数据库连接属性用于创建数据库连接

Datasource.java数据源.java

@Value("${spring.app.datasource.url}")
private String url;
@Value("${spring.app.datasource.driver-class-name}")
private String className;
@Value("${spring.app.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.app.jpa.properties.hibernate.dialect}")
private String dialect;

controller class controller class

@RestController
public class Controller {
    @Value("${spring.property.name}")
    private String name;
    @Value("${spring.property.enable}")
    private boolean status;

    public void validateObject(String surName) {
        if (status) {                              # if this flag is true then only process
            System.out.println("name= " + name);
            System.out.println("surName= " + surName);
        }
    }

ControllerTest.java控制器Test.java

@SpringBootTest
class ControllerTest {
    @Autowired
    private Controller controller;
    @Test
    void show() {
        controller.validateObject("sharma");
    }

by default the flag is false, so every time test case runs it never processes the object.默认情况下,该标志为 false,因此每次运行测试用例时它都不会处理 object。 so I tried to create aplication.properties in the test folder所以我尝试在测试文件夹中创建 aplication.properties

\src\test\resources\application.properties \src\test\resources\application.properties

spring.property.name=vishal
spring.property.enable=true

but now it's giving me an error that但现在它给了我一个错误

Could not resolve placeholder 'spring.app.datasource.url'

but I don't want to provide DB connection URL, I am not connecting to the database while testing.但我不想提供数据库连接 URL,我在测试时没有连接到数据库。

Q1 - how to change the value of properties file for test case only. Q1 - 如何仅更改测试用例的属性文件的值。

Q2 - is it mandatory to provide all the keys of \src\main\resources\application.properties is \src\test\resources\application.properties? Q2 - 是否必须提供 \src\main\resources\application.properties 的所有键是 \src\test\resources\application.properties?

I am new in test case, so little explained answers would be welcomed.我是测试用例的新手,所以很少有解释的答案会受到欢迎。

Update:- I found that更新:-我发现

@SpringBootTest
@TestPropertySource(properties = {"spring.property.name=vishal", " spring.property.status=true"})
class ControllerTest {

will solve the issue temporarily, by providing keys along with values, but I have a lot of keys, which cannot be provided in such a way.将通过提供键和值来暂时解决问题,但是我有很多键,无法以这种方式提供。

If you use @SpringBootTest then your test will load the whole Spring context.如果您使用@SpringBootTest ,那么您的测试将加载整个 Spring 上下文。 This means it will create all your beans and try to wire them together.这意味着它将创建您所有的 bean 并尝试将它们连接在一起。 If you inject property values to your beans, you have to specify them all for such tests as otherwise, you won't be able to boot the application.如果将属性值注入到 bean,则必须为此类测试指定所有属性值,否则将无法启动应用程序。

What might help you in such a situation is to use test annotations like @WebMvcTest or @DataJpaTest to focus on testing just slices of your application.在这种情况下可能对您有所帮助的是使用@WebMvcTest@DataJpaTest类的测试注释来专注于测试应用程序的片段。 Using @WebMvcTest you'll get an application context just containing controllers and everything related to your web layer.使用@WebMvcTest ,您将获得一个应用程序上下文,其中仅包含控制器以及与您的 web 层相关的所有内容。 Other beans (like service classes) can be mocked with @MockedBean .可以使用@MockedBean其他 bean(如服务类)。

Next, for testing business logic in service classes try not to use @SpringBootTest and rather rely on plain JUnit 5 and Mockito to verify your code.接下来,为了测试服务类中的业务逻辑,尽量不要使用@SpringBootTest ,而是依靠普通的 JUnit 5 和 Mockito 来验证您的代码。

You still might want to have some integration tests that use @SpringBootTest to make sure everything is working together.您仍然可能希望进行一些使用@SpringBootTest的集成测试,以确保一切正常工作。 In such case, you can hard code any static property inside application.properties in src/test/resources/ or using the annotation like you already did: @TestPropertySource(properties = {"spring.property.name=vishal", " spring.property.status=true"}) .在这种情况下,您可以在src/test/resources/中的application.properties中对任何 static 属性进行硬编码,或者使用您已经做过的注释: @TestPropertySource(properties = {"spring.property.name=vishal", " spring.property.status=true"})

When it comes to providing a database, you can either configure an embedded database (which I would try to avoid) or use the same database as in production.在提供数据库时,您可以配置嵌入式数据库(我会尽量避免)或使用与生产中相同的数据库。 Testcontainers helps you a lot when it comes to providing external infrastructure for your tests like a database.在为您的测试提供外部基础设施(如数据库)时, Testcontainers可以为您提供很多帮助。

An example setup with Spring Boot >= 2.2.6 and JUnit might look like the following: Spring Boot >= 2.2.6 和 JUnit 的示例设置可能如下所示:

@Testcontainers
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationIT {
 
  @Container
  public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer()
    .withPassword("password")
    .withUsername("username");
 
  @DynamicPropertySource
  static void postgresqlProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", postgreSQLContainer::getJdbcUrl);
    registry.add("spring.datasource.password", postgreSQLContainer::getPassword);
    registry.add("spring.datasource.username", postgreSQLContainer::getUsername);
  }
 
  @Test
  public void contextLoads() {
  }
 
}

For Junit5, annotate your test class with path to application.properties in your src/main/resources :对于 Junit5,在您的src/main/resources中使用application.properties的路径注释您的测试 class :

@ExtendWith(SpringExtension.class)
@TestPropertySource("classpath:application.properties")
public class MyTest {
    @Value("${property.name}")
    private int myProperty;
    tests...
}

property gets loaded属性被加载

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Batch JUnit测试未加载JobLauncherTestUtils的application.properties - Spring Batch JUnit test not loading application.properties for JobLauncherTestUtils Spring Boot 访问 application.properties 以进行 JUnit 测试 - Spring Boot accessing application.properties for JUnit Test 运行Junit测试用例时未设置Spring 4 application.properties @Value - Spring 4 application.properties @Value is not set when running Junit test case 在 Junit 测试中覆盖默认的 Spring-Boot application.properties 设置 - Override default Spring-Boot application.properties settings in Junit Test 使用动态值覆盖 Junit 测试中的默认 Spring-Boot application.properties 设置 - Override default Spring-Boot application.properties settings in Junit Test with dynamic value mvn test - 覆盖 application.properties 中的值 - mvn test - override values in application.properties 如何在 Mockito 测试中从 application.properties 加载属性 - How to load the properties from application.properties in Mockito test 如何将test / java / application.properties中的某些字段链接到main / java / application.properties中的相同字段? - How to link some field in test/java/application.properties to the same field in main/java/application.properties? application.properties 中的注释 - Comments in application.properties Spring-boot - 参数化测试 - 访问MethodSource中的Application.properties - Spring-boot - Parameterized Test - Access Application.properties in MethodSource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM