1

如果我实际上没有像count must_== 1在 Specs2 测试中那样的显式断言,我会收到一个错误,表明找不到隐式断言。

// doesn't compile
class Example extends Specification {
  "You need an assertion" >> {
    // hello!
  }
}

很公平。

但是如果我也使用 scalamock 的MockContext,我可以只依赖期望而不是断言;模拟某些东西,scalamock 将验证方法是否被调用等;

class MockExample extends Specification {
  "I can use 'expectations' here instead" in new MockContext {
    val foo = mock[Foo]
    (foo.bar _).expects(*).once
    // no explicit assertions
  }     
}

但是,如果我尝试通过混合来共享上下文设置IsolatedMockFactory,我又回到了编译器故障。任何想法如何解决它?

// doesn't compile
class AnotherMockExample extends Specification with IsolatedMockFactory {
  val foo = mock[Foo]
  "I can't use 'expectations' here any more" >> {        
    (foo.bar _).expects(*).once
  }  
}
4

1 回答 1

1

specs2 中的一个示例接受具有org.specs2.execute.AsResult类型类实例的任何内容。由于(foo.bar _).expects.onceis 类型CallHandler,您可以为其创建一个AsResult实例CallHandler,只评估值并返回Success

 implicit def CallHandlerAsResult[R : Defaultable]: AsResult[CallHandler[R]] = new AsResult {
    def asResult(c: =>CallHandler[R]) = {
      c
      Success
    }
 }

由于在 ScalaMock 中失败是基于异常的,如果不满足某些模拟期望,这应该会导致抛出异常。

于 2015-05-12T22:33:43.920 回答