gpt4 book ai didi

scala - 为什么这个 specs2 测试使用 Mockito 通过?

转载 作者:行者123 更新时间:2023-12-03 16:07:01 25 4
gpt4 key购买 nike

假设我有这个接口(interface)和类:

abstract class SomeInterface{
def doSomething : Unit
}

class ClassBeingTested(interface : SomeInterface){
def doSomethingWithInterface : Unit = {
Unit
}
}

请注意,doSomethingWithInterface 方法实际上并没有对接口(interface)做任何事情。

我为它创建了一个测试,如下所示:
import org.specs2.mutable._
import org.specs2.mock._
import org.mockito.Matchers
import org.specs2.specification.Scope

trait TestEnvironment extends Scope with Mockito{
val interface = mock[SomeInterface]
val test = new ClassBeingTested(interface)
}

class ClassBeingTestedSpec extends Specification{
"The ClassBeingTested" should {
"#doSomethingWithInterface" in {
"calls the doSomething method of the given interface" in new TestEnvironment {
test.doSomethingWithInterface
there was one(interface).doSomething
}
}
}
}

该测试通过。为什么?我设置错了吗?

当我摆脱范围时:
class ClassBeingTestedSpec extends Specification with Mockito{
"The ClassBeingTested" should {
"#doSomethingWithInterface" in {
"calls the doSomething method of the given interface" in {
val interface = mock[SomeInterface]
val test = new ClassBeingTested(interface)
test.doSomethingWithInterface
there was one(interface).doSomething
}
}
}
}

测试按预期失败:
[info]   x calls the doSomething method of the given interface
[error] The mock was not called as expected:
[error] Wanted but not invoked:
[error] someInterface.doSomething();

这两个测试有什么区别?为什么第一个应该失败时通过了?这不是 Scopes 的预期用途吗?

最佳答案

当你混入 Mockito特质到另一个特质,你可以创造像 there was one(interface).doSomething 这样的期望.如果这样的表达式失败,它只会返回 Result ,它不会抛出 Exception .然后它会在 Scope 中丢失。因为它只是特征体内的“纯”值。

但是,如果您混入 Mockito mutable.Specification 的特征然后在失败时会抛出异常。这是因为 mutable.Specification类指定应该有 ThrownExpectations通过混合这种特性。

因此,如果您想创建一个扩展两个 Scope 的特征您可以:

  • 从规范内部创建特征,而不是让它扩展 Mockito:
    class MySpec extends mutable.Specification with Mockito {
    trait TestEnvironment extends Scope {
    val interface = mock[SomeInterface]
    val test = new ClassBeingTested(interface)
    }
    ...
    }
  • 像你一样创建特征和规范,但要混入 org.specs2.execute.ThrownExpectations
    trait TestEnvironment extends Scope with Mockito with ThrownExpectations {
    val interface = mock[SomeInterface]
    val test = new ClassBeingTested(interface)
    }

    class MySpec extends mutable.Specification with Mockito {
    ...
    }
  • 关于scala - 为什么这个 specs2 测试使用 Mockito 通过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20429435/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com