简体   繁体   中英

Is it possible to stub or mock a method of a class under test?

In this Scala class

class A{
def a() = {b();}
def b() = {...}
}

If I want to test a() , is it possible to mock or stub b()

Mocks override all methods (usually with return null unless explicitly stated to return something else ) while here you want to override just one method. Since your class isn't final it would be easier to do something like

val tested: A = new A {
  override def b = ...
}

than mock it (actually mocking final classes is also impossible without something like PowerMock)

val tested = mock[A]
(tested.b _) returning (...)
// tested.a returns null and ignores b

because mock would also override a making your tests useless. You could "fix" it by mocking a to have the same implementation as the original... but this is absurd for many reasons.

So mocking method of a tested class with a mocking framework is possible but it's getting in the way rather than helping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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