简体   繁体   English

从specs2中的隐式类模拟方法

[英]Mock a method from implicit class in specs2

Say I have a class and a related implicit class: 说我有一个类和一个相关的隐式类:

class Project
implicit class RichProject(p:Project) {
  def searchFile(keyword:String):Seq[File] = {
    p.getFiles.filter(_.name.contains(keyword))
  }
}

Then I want to mock the searchFile method for a project in a specs2 test: 然后,我想在specs2测试中模拟projectsearchFile方法:

val project = mock[Project]
project.searchFile("aa") returns Seq(new File("/aaa"))

But it reports a NullPointException that seems it's running inside the real searchFile instead of mocking it. 但它报告了一个NullPointException ,它似乎在真正的searchFile运行,而不是对其进行searchFile

Is it possible to fix it? 有可能修复它吗?

When you write project.searchFile then searchFile is not a method which belongs to the mocked object but to the RichProject class. 当您编写project.searchFile searchFile不是属于RichProject对象的方法,而是属于RichProject类的方法。 So Mockito can not mock it and will try to execute it. 因此,Mockito无法模拟它,并将尝试执行它。

I don't fix there is a fix for this other than mocking the RichProject class itself. 除了RichProject类本身之外,我没有解决此问题的其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM