AdSense

網頁

2020/10/9

Spring Boot 用@TestPropertySource修改測試用的properties參數

Spring Boot測試類可使用@TestPropertySource修改測試時使用的properties參數值。

application.properties原本有一自訂參數為app.name的值為Demo Application

application.properties

app.name=Demo Application

DemoServicegetAppName()方法回傳此參數值。

DemoService

package com.abc.demo.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class DemoService {

    @Value("${app.name}")
    private String appName;

    public String getAppName() {
        return appName;
    }

}

DemoService的測試類DemoServiceTests如果不想用原本的參數值測試,可透過@TestPropertySourceproperties屬性修改app.name的值為Test Application如下。

DemoServiceTests

package com.abc.demo.service;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;

@TestPropertySource(properties = "app.name=Test Application")
@SpringBootTest
class DemoServiceTests {

    @Autowired
    private DemoService demoService;

    @Test
    void getAppName_test() {

        String appName = demoService.getAppName();
        Assertions.assertEquals("Test Application", appName);

    }
}

則在執行DemoServiceTests中的測試方法時,app.name會變為Test Application


github


沒有留言:

AdSense