简体   繁体   English

是否可以使用 ScalaMock 模拟/存根同一测试类的方法?

[英]Is it possible to mock / stub methods of the same test class with ScalaMock?

With Mockito and other testing frameworks there are usually ways to mock functionality of a method within the test class.对于 Mockito 和其他测试框架,通常有多种方法可以模拟测试类中方法的功能。 I couldn't seem to get ScalaMock to accept the same way.我似乎无法让 ScalaMock 以同样的方式接受。

class A {
 def methodUnderTest()
 def methodUsedInMethodUnderTest()
}

Then in the test class I'm:然后在测试课中我是:

(A.methodUsedInMethodUnderTest _)
.expects.....
a.methodUnderTest shouldEqual ..

I know that if you are mocking / stubbing out the class and then calling the same functionality on a real instance this won't work.我知道,如果您模拟/删除类,然后在真实实例上调用相同的功能,这将不起作用。 But there are workarounds by using mocks for both calls etc.但是通过对两个调用等使用模拟有一些解决方法。

If this is the wrong approach, what would be the best way to test a method that uses other methods in the same test class?如果这是错误的方法,那么测试在同一测试类中使用其他方法的方法的最佳方法是什么? I thought that decoupling the methods was the best practice.我认为将方法解耦是最佳实践。

Thanks!谢谢!

If I understand your question correctly, you can create a mock of A and then tell ScalaMock to execute the real implementation of methodUnderTest .如果我没有理解你的问题,你可以创建一个模拟A ,然后告诉ScalaMock执行真正落实methodUnderTest

val aMock = mock[A]

when(aMock.methodUnderTest).thenCallRealMethod()
when(aMock.methodUsedInMethodUnderTest).thenReturn(someValue)

aMock.methodUnderTest shouldEqual someOtherValue

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

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