Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

scalamock - Should I Mock the Trait or Mock the Class Using Scala Mock

Say I have the following:

@ImplementedBy(classOf[DefaultFoo])
trait Foo {
  def a (s : String) : Int
}

class DefaultFoo @Inject()() extends Foo{

  override def a (s : String) = 1

}

@ImplementedBy(classOf[DefaultBaz])
trait Baz {
  def b (s : String) : Int
}

class DefaultBaz @Inject()(val f :Foo) extends Baz{

  override def a (s : String) = 1

}

If I want to test, say DefaultBaz, I am normally using ScalaMock and I would mock as follows in my test spec:

class DefaultBazSpec extends AnyWordSpec with MockFactory{

   val mockFoo = mock[Foo]
val b = new DefaultBaz(mockFoo)

   // write tests
}

But I could also do this:

val mockFoo = mock[DefaultFoo]

Which one is better? Mock the trait or the default class implementation?

question from:https://stackoverflow.com/questions/65890369/should-i-mock-the-trait-or-mock-the-class-using-scala-mock

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Better to use neither. Mocking should be in general avoided (especially in Scala).

But even if you decided to proceed with mocks, mocking the class under test destroys the whole purpose of testing: the code under test has nothing in common with the production code.

Mocks are for mocking dependencies (e.g. constructor parameters or method arguments) of the class under test.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...