使用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
即可。让我假装我更喜欢动词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 {
???
}
,只是因为它在ScalaTest User Guide中使用
我们可能会标准化一天。但就目前而言,是否有可能在发生冲突时排除匹配器?
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 => _}
注意:我试图通过{{1}}排除MustMatchers,但这对编译错误没有影响。
答案 0 :(得分:1)
我认为你不能,因为这两个类都没有继承另一个。显而易见的方法是添加一个额外的类型:
// 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)
}
}
注意:我试图通过导入org.scalatest排除MustMatchers。{MustMatchers =&gt; _}但这对编译错误没有影响。
您无法通过导入删除继承的成员。如果您通过导入OurCommonTestHelpers
来访问它们,则不会在MyBizLogicTest
中导入它们(但需要在需要它们的其他类中导入)。