Springboot中单元测试处理@value简单方式,实际可操作方式很多,仅提供其中一种简单的方式作为参考,有不妥之处望指正。
工程结构
custom.properties文件中有如下配置
custom.task.size=10
service方法中通过@value方式注入该配置值
/**
* description SayHelloServices impl
*
* @author loongshawn
* @date 2019-01-24
*/
@Service
public class SayHelloServiceImpl implements SayHelloService {
@Value("custom.task.size")
String taskSize;
@Override
public String sayHello(String helloArgs) {
String cmpArgs = "hello";
if (cmpArgs.equals(helloArgs)){
return "hello";
} else {
return "bye bye";
}
}
@Override
public String getTaskSize() {
return taskSize;
}
单测用例
/**
* description
*
* @author loongshawn
* @date 2019-01-24
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SayHelloServiceTest {
@InjectMocks
private SayHelloServiceImpl sayHelloService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(sayHelloService,"taskSize","10");
}
@Test
public void testGetTaskSize() {
String taskSize = sayHelloService.getTaskSize();
Assert.assertTrue(!StringUtils.isEmpty(taskSize));
}
}