簡體   English   中英

如何在 Mockito 測試中從 application.properties 加載屬性

[英]How to load the properties from application.properties in Mockito test

我正在嘗試編寫單元測試用例來測試該方法,但遇到了問題。

這是示例代碼:

我的服務1

@Service
public class MyService1 {

    @Autowired
    private ServiceProperties serviceProperties;

    public void getMyLanguage(){
        String language =  serviceProperties.getLocale().getLanguage();
        printSomething(language);
    }

    private void printSomething(String input){
        System.out.print("your current language is " + input);
    }
}

服務屬性

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Locale;

@ConfigurationProperties(prefix = "conversation")
public class ServiceProperties {

    private ServiceProperties(){};

    private Locale locale;

    public Locale getLocale(){

        return locale;

    }
}

應用程序屬性

conversation.locale=en_US

這是我的測試用例:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MyService1Test {
    @Mock
    private ServiceProperties serviceProperties;

    @InjectMocks
    private MyService1 myService1;

    @Test
    public void getMyLanguage(){
        when(serviceProperties.getLocale().getLanguage()).thenReturn("EN");
        myService1.getMyLanguage();
        verify(myService1).getMyLanguage();
    }
}

測試會觸發nullpointerexception,因為測試中沒有加載locale的屬性,如果我不想啟動服務器(使用@SpringBootTest注解)加載上下文,有沒有辦法解決這個問題,誰能幫忙?

問題出在這一行:

when(serviceProperties.getLocale().getLanguage()).thenReturn("EN");

因為serviceProperties被模擬,所以serviceProperties.getLocale()等於null 所以當serviceProperties.getLocale().getLanguage()被調用時你會得到NullPointerException

一種解決方法如下:

@RunWith(MockitoJUnitRunner.class)
public class MyService1Test {
    @Mock
    private ServiceProperties serviceProperties;
    @InjectMocks
    private MyService1 myService1;

    @Test
    public void getMyLanguage(){
        when(serviceProperties.getLocale()).thenReturn(new Locale("EN"));
        myService1.getMyLanguage();
        verify(myService1).getMyLanguage();
    }
}

現場注入不便於測試。 您可以使用構造函數注入

@Service
public class MyService {


    private final ServiceProperties serviceProperties;

    @Autowired
    public MyService(ServiceProperties serviceProperties) {
        this.serviceProperties = serviceProperties;
    }
    //...
}

然后你將能夠在每次測試之前注入模擬

@RunWith(MockitoJUnitRunner.class)
public class MyService1Test {
    @Mock
    private ServiceProperties serviceProperties;

    private MyService1 myService1;

    @Before
    public void createService(){
        myService1 = new MyService1(serviceProperties);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM