【问题标题】:Springboot unit test set @Configuration Properties dynamicallySpring Boot 单元测试动态设置@Configuration Properties
【发布时间】:2019-04-10 06:52:34
【问题描述】:

我有一个在命令行上运行的 springboot 2 应用程序。命令行参数之一是 fileName,命名中带有 batchNo。我正在使用命令行 arg 中的 fileName 设置我的 application.properties 文件名值。示例batch-1234.csv

在我的 ApplicationConfig 文件中,我正在从 applications.properties 文件中读取文件名,如下所示。

@ToString
@Setter
@Getter
@Configuration
@ConfigurationProperties(prefix = "hri")
public class ApplicationConfig {

    @Value("${company.file}")
    private String file;

    public String getBatchNo() {
        return parseBatchNo(file);
    }

    public String getHomecareDetailPath() {
        return filePathProvider.getFilePath("batch-" + getBatchNo() + ".csv");
    }

    private static String parseBatchNo(String file) {
        if (batchNo == null) {
            batchNo = file.substring((file.lastIndexOf("-") + 1), (file.length() - 4));
        }
        return batchNo;
    }
}

我的目标是能够为每个单独的测试动态设置此文件名。

例子

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AdapLoadApplication.class)
@AutoConfigureTestDatabase
public class CorporateServiceTest {

    @Autowired
    private ApplicationConfig config; 

    @Test
    public void convertCsvToBean() throws IOException {
        // Set file
        config.setFile("batch-9999.csv");
    }

    @Test
    // Is there an annotation to set the Application.properties file for each test?
    public void test2() throws IOException {
        //Set file
        config.setFile("batch-8888.csv");
    }
}

如何动态设置文件以便更好地管理测试?目前我们使用的是同一个文件,并且不得不做大量的文件复制覆盖一个测试文件。

我想澄清一下,我不只是想在我的测试类中创建一个新的 ApplicationConfig bean 并设置文件并从每个单独的测试中读取相同的文件。我想在每个单独的测试开始时设置该文件名。

【问题讨论】:

标签: java unit-testing spring-boot


【解决方案1】:

例如你可以使用环境:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AdapLoadApplication.class)
@AutoConfigureTestDatabase
public class CorporateServiceTest {

    @Autowired
    private ApplicationConfig config;

    @Resource
    private Environment env;

    @Test
    public void convertCsvToBean() throws IOException {
        //Set file
        config.setFile(env.getProperty("first_test_company.file"));
    }

    @Test
    //Is there an annotation to set the Application.properties file for each test?
    public void test2() throws IOException {
        //Set file
        config.setFile(env.getProperty("second_test_company.file"));
    }
}

您必须使用@Resource,因为@Autowired 在这种情况下不起作用。

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2020-01-23
    • 2019-01-20
    • 1970-01-01
    相关资源
    最近更新 更多