我在模拟服务中有一种方法,
def whenDynamoDBActionBlacklist(newlist: List[String]) = {
doReturn(newlist).when(service).Blacklist
}
并希望通过使用进行测试
val list = mocks.whenDynamoDBActionBlacklist(List("333:avd"))
但我无法获取值,获取了nullPointerException,有人可以帮助我吗?谢谢。
我相信您会混淆模拟设置和模拟执行之间的区别。whenDynamoDBActionBlacklist
实际上并不会返回值,而是只为存根方法指定响应。考虑下面的例子
import org.mockito.{ArgumentMatchersSugar, IdiomaticMockito}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class MockitoScalaExampleSpec extends AnyFlatSpec with Matchers with IdiomaticMockito with ArgumentMatchersSugar {
"MockitoScalaExample" should "demonstrated difference between mock setup and mock execution" in {
// system under test
trait MyService {
def blacklist: List[String]
}
// initialise mock of the system under test
val serviceMock = mock[MyService]
// specify behaviour of the mock by defining how should stubbed methods respond
serviceMock.blacklist returns List("mocked!")
// actually execute the mocked system under test
val result = serviceMock.blacklist
// assert on the result
result should be(List("mocked!"))
}
}
关键是要了解
serviceMock.blacklist returns List("mocked!")
尚未返回,List("mocked!")
但声明一旦调用将发生什么aMock.blacklist
。
请注意,该示例使用了Mockito-scala,但是在香草Mockito中也应用了相同的概念。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句