【问题标题】:Mock Service class that has Autowired dependencies具有自动装配依赖项的模拟服务类
【发布时间】:2021-03-23 15:56:50
【问题描述】:

我有一个服务类和一个配置类,如下所示:

public class MyService{

 @Autowired
 MyConfig myconfig;

 @Autowired
 private WebClient webClient;

 private String result;

 public String fetchResult(){
   return webClient.get().uri(myConfig.getUrl()).retrieve().bodyToMono(String.class).block();
 }
}

@ConfigurationProperties("prefix="somefield")
@Component
class MyConfig{
   private String url;
   //getter & setter
  }
}

下面是 Junit:

@Runwith(MockitoJUnitRunner.class)
public class TestMe{

    @InjectMocks
    MyService myService;

    @Test
    public void myTest(){
       when(myService.fetchResult().then return("dummy");
    }
}

当我在服务类的 webClient 上运行此类时,我收到空指针错误。 可能是什么问题。我是 JUnits 的新手。 我该如何为此编写合适的 JUnit。

【问题讨论】:

  • 您提出的测试没有什么意义。您只在被测对象上存根了一种方法。你得到了 NPE,这是理所当然的——你用未初始化的成员在被测对象上调用了一个方法。 NPE 涵盖了另一个问题:您正试图在一个非模拟对象上存根方法!

标签: java junit nullpointerexception mockito junit4


【解决方案1】:

使类可测试的最简单方法是使用构造函数注入

public class MyService{
  private final MyConfig myconfig;
  private final WebClient webClient;
  private String result;

  @AutoWired
  MyService(
    MyConfig myconfig,
    WebClient webClient
  ) {
    this.myconfig = myconfig;
    this.webClient = webClient;
  }

  ...
}

【讨论】:

  • 这对我有用。一个疑问,如果我在 MyService 类中有 stepExecution,我如何从 Junit 调用它?它正在给 NPE。
  • 就在myService.stepExecution。我看了你的问题,你的测试把 myService 当作一个模拟。您应该清楚要模拟哪些内容以及要测试哪些内容。
  • 我已经更改了我的测试用例,现在我正在通过构造函数使用自动装配。但现在在服务类中使用的 spring 批处理的 stepexecution 中卡在 NPE 中。
  • 是的,我在几分钟后阅读了它,并按照文档中的建议使用 MetaDataInstanceFactory 解决了它。非常感谢您的努力和时间。
猜你喜欢
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 2020-03-28
  • 2022-11-26
相关资源
最近更新 更多