Freewind
Freewind

Reputation: 198198

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:

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.

Is it possible to fix it?

Upvotes: 2

Views: 1122

Answers (1)

Eric
Eric

Reputation: 15557

When you write project.searchFile then searchFile is not a method which belongs to the mocked object but to the RichProject class. So Mockito can not mock it and will try to execute it.

I don't fix there is a fix for this other than mocking the RichProject class itself.

Upvotes: 3

Related Questions