score:2

the issue is that extension methods are basically a syntactic sugar.

i will be explaining using an example.

trait foo
implicit class fooimplicit(foo: foo) {
  def bar: string = "bar
}

foo.bar

is translated to

new fooimplicit(foo).bar

so mocking:

mockito.when(foo.bar).thenreturn("bad")

becomes:

mockito.when(new fooimplicit(foo).bar).thenreturn("bad")

note how foo.bar is treated and that's the issue.

is it possible to achieve what i want in the current setup?

no, i don't think it is possible in the current setup.

if not, how should i refactor my code

the only way to achieve that is to use implicit conversions rather than implicit classes.

i will be showing an example how this could be achieved:

trait foo {
  def bar: string
}

object implicitfoo {
  object implicits {
    implicit footofooimplicit(foo: foo): fooops = new fooimplicit(foo)
    class fooimplicit(foo: foo) {
      def bar: string = "bar"
    }
  }
}

and your test

import org.scalatest.wordspec
import org.mockito.mockitosugar

  class myspec extends wordspec with mockitosugar {
    "my mock" should {
      "handle methods from implicit classes" in {
        val fooops = mock[fooimplicit]
        implicit footoops(foo: foo): fooimplicit = fooops
        val foo = mock[foo]
        when(foo.bar) thenreturn "bad" // works
      }
    }
  }

in your production you need to get an implicit parameter of the shape foo => fooimplicit so when you call that method from the test the actual implicit mock is provided...

if i test in a different class the methods available in the implicit class, does it make sense to test the readsometable and the mainmethod inside myobject?

i do not think that you require to test the readsometable and the mainmethod inside myobject.but other way round is true.

let me know if it helps!!


Related Query

More Query from same tag