我正在尝试编写一个单元测试用例来测试该方法,但我遇到了问题。
这是示例代码:
myService1
@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);
}
}
ServiceProperties
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;
}
}
application.properties
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,因为我不想启动服务器(使用@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);
}
}