ScalaTest 如何在混合多个匹配器时排除 MustMatchers

ScalaTest how to exclude MustMatchers if multiple Matchers are mixed in

使用 Scalatest 2.2.5、Scala 2.11.8、sbt 0.13.13、JDK 1.8.121

我们的代码库不断发展,开发人员对测试风格和匹配器有不同的偏好。在下面的代码中,测试使用 Matchers,它还需要在其声明中混入一个 trait OurCommonTestHelpers,如果自己混入 MustMatchers。很容易解决,把with Matchers去掉,把should equal换成must equal就可以了。假设我更喜欢动词 should,只是因为它用在 ScalaTest User Guide

我们可能有一天会标准化。但是现在,是否可以在发生冲突时排除匹配器?

import org.scalatest.{FreeSpec, Matchers}

class MyBizLogicTest extends FreeSpec 
with Matchers // <-- conflict with MustMatchers from trait OurCommonTestHelpers  
with OurCommonTestHelpers 
{
  "A trivial addition" in {
      (1 + 2) should equal (3)
  }
}

trait OurCommonTestHelpers extends MockitoSugar with MustMatchers {
  ???
} 

代码编译失败:

Error:(26, 7) class MyBizLogicTest inherits conflicting members:
  method convertSymbolToHavePropertyMatcherGenerator in trait Matchers of type (symbol: Symbol)MyBizLogicTest.this.HavePropertyMatcherGenerator  and
  method convertSymbolToHavePropertyMatcherGenerator in trait MustMatchers of type (symbol: Symbol)MyBizLogicTest.this.HavePropertyMatcherGenerator
(Note: this can be resolved by declaring an override in class MyBizLogicTest.);
 other members with override errors are: equal, key, value, a, an, theSameInstanceAs, regex, <, >, <=, >=, definedAt, evaluating, produce, oneOf, atLeastOneOf, noneOf, theSameElementsAs, theSameElementsInOrderAs, only, inOrderOnly, allOf, inOrder, atMostOneOf, thrownBy, message, all, atLeast, every, exactly, no, between, atMost, the, convertToRegexWrapper, of
class MyBizLogicTest extends FreeSpec

注意:我试图通过 import org.scalatest.{MustMatchers => _} 排除 MustMatchers,但这对编译错误没有影响。

我认为你做不到,因为 class 都没有继承另一个。显而易见的方法是添加一个额外的类型:

// name just to be clear, I don't suggest actually using this one
trait OurCommonTestHelpersWithoutMatchers extends ... {
  // everything in OurCommonTestHelpers which doesn't depend on MustMatchers
}

trait OurCommonTestHelpers extends OurCommonTestHelpersWithoutMatchers with MustMatchers {
  ...
}

class MyBizLogicTest extends FreeSpec 
with Matchers 
with OurCommonTestHelpersWithoutMatchers 
{
  "A trivial addition" in {
      (1 + 2) should equal (3)
  }
}

NOTE: I have tried to exclude the MustMatchers by import org.scalatest.{MustMatchers => _} but this has no effect on the compile error.

您不能通过不导入 来删除继承的 成员。如果您通过在 OurCommonTestHelpers 中导入来访问它们,您根本不会在 MyBizLogicTest 中导入它们(但需要在您需要它们的其他 class 中导入)。