【发布时间】:2016-12-17 07:20:12
【问题描述】:
在过去的几天里,我一直在注释/嘲笑地狱。我遇到了以下问题:
Failed to instantiate [com.test.service.util.Utils]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: value1 cannot be null
我正在为其中包含 Utils 类的 Service 类编写模拟测试。这个 Utils 类依赖于 Spring 应用程序属性文件中的一个值。在我看来,@Value 成员被注入为空。如何用参数实例化一个对象并在 Spring 中模拟它?
Service.java 看起来像这样:
@Service
public class Service {
@Value("${value1}")
private String value1;
private Utils utils = new Utils(value1);
public service_method1() {
utils.utils_method1();
}
}
Utils 类如下所示:
@Component
public class Utils {
private OtherUtils otherUtils;
public Utils(String value1) {
otherUtils = new OtherUtils(value1);
}
public utils_method1() {
otherUtils.otherUtils_method1()
}
}
ServiceTests.java 如下所示:
public class ServiceTests {
private String VALUE1 = "value1";
@Mock
private Utils utils = new Utils(value1);
@InjectMocks
private Service service;
@Test test_method1() {
//set up mocks for Utils methods
//run Service class methods
}
}
【问题讨论】:
-
在您的测试中尝试使用
@Spy而不是@Mock作为utils成员变量。 -
为快速响应干杯,但仍然没有骰子。我删除了所有 @Autowire 注释,是否需要这些注释?
标签: java spring spring-boot mockito