我正在尝试编写一个单元测试用例来测试该方法,但是遇到问题。
这是示例代码:
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);
}
}
服务属性
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批注)来加载上下文,是否有任何方法可以解决此问题,有人可以帮忙吗?
答案 0 :(得分:1)
问题出在这一行:
when(serviceProperties.getLocale().getLanguage()).thenReturn("EN");
由于serviceProperties
被嘲笑,因此serviceProperties.getLocale()
等于null
。因此,在调用NullPointerException
时得到serviceProperties.getLocale().getLanguage()
。
一种解决方法如下:
@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();
}
}
答案 1 :(得分:0)
现场注入不便于测试。您可以使用构造函数注入
@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);
}
}