【问题标题】:How to Instantiate and Mock Objects with Arguments in Spring如何在 Spring 中使用参数实例化和模拟对象
【发布时间】: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


【解决方案1】:

您不需要在Service 中创建Utils 的对象,而是可以autowire 它,因此将
private Utils utils = new Utils(value1); 替换为

@Autowire
private Utils utils;


如果您想要 Utils 中的 value1,请移动

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

Utils

最后设置私有属性使用 ReflectionTestUtils from spring ReflectionTestUtils.setField(targetObject, name, value);

【讨论】:

  • 您好乔宾,感谢您的回复。我正在尝试您概述的内容,我在哪里使用 ReflectionTestUtils.setField(targetObject, name, value);在什么类/方法中?谢谢
  • 在测试课中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
相关资源
最近更新 更多