如何在Spring中实例化和模拟具有参数的对象

时间:2016-12-17 07:20:13

标签: java spring spring-boot mockito

在过去的几天里,我一直在注释/嘲笑地狱。我遇到了以下问题:

Failed to instantiate [com.test.service.util.Utils]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: value1 cannot be null

我正在为Service类编写模拟测试,其中包含一个Utils类。此Utils类依赖于Spring应用程序属性文件中的值。在我看来@Value成员被注入为null。如何使用参数实例化对象并在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
}

}

1 个答案:

答案 0 :(得分:0)

您不需要在Utils中创建Service的对象,而是可以autowire,因此将<{1}}替换为

private Utils utils = new Utils(value1);


如果您想要@Autowire private Utils utils; 中的value1,请移动

Utils

@Value("${value1}") private String value1;

最后从spring Utils

设置私有属性使用ReflectionTestUtils
相关问题