如何使用scala进行instanceof检查(test)

83qze16e  于 2021-07-14  发布在  Java
关注(0)|答案(6)|浏览(407)

我正在尝试将scalatest合并到我的java项目中;用scalatests替换所有junit测试。有一次,我想检查guice的注入器是否注入了正确的类型。在java中,我有这样一个测试:

public class InjectorBehaviour {
    @Test
    public void shouldInjectCorrectTypes() {
        Injector injector = Guice.createInjector(new ModuleImpl());
        House house = injector.getInstance(House.class);

        assertTrue(house.door() instanceof WoodenDoor);
        assertTrue(house.window() instanceof BambooWindow);
        assertTrue(house.roof() instanceof SlateRoof);
    }
}

但我对scalatest也有同样的问题:

class InjectorSpec extends Spec {
    describe("An injector") {
        it("should inject the correct types") {
            val injector = Guice.createInjector(new ModuleImpl)
            val house = injector.getInstance(classOf[House])

            assert(house.door instanceof WoodenDoor)
            assert(house.window instanceof BambooWindow)
            assert(house.roof instanceof SlateRoof)
        }
    }
}

它抱怨说 instanceof 不是的成员 Door / Window / Roof . 我不能用吗 instanceof 在斯卡拉那边?

gorkyyrv

gorkyyrv1#

如果您不想像junit那样,并且希望使用scalatest的匹配器,那么可以编写自己的属性匹配器来匹配类型(条类型擦除)。
我发现这条线索非常有用:http://groups.google.com/group/scalatest-users/browse_thread/thread/52b75133a5c70786/1440504527566dea?#1440504527566dea
然后可以编写如下Assert:

house.door should be (anInstanceOf[WoodenDoor])

而不是

assert(house.door instanceof WoodenDoor)
n53p2ov0

n53p2ov02#

关于isinstanceof[type]和junit advice的最新答案很好,但我想补充一点(对于以非junit相关身份访问此页面的人)。在许多情况下,scala模式匹配将满足您的需要。在这种情况下,我会推荐它,因为它给你免费的排版,减少了出错的空间。
例子:

OuterType foo = blah
foo match {
  case subFoo : SubType => {
    subFoo.thingSubTypeDoes // no need to cast, use match variable
  }
  case subFoo => {
    // fallthrough code
  }
}
t9aqgxwy

t9aqgxwy3#

将guillaume的scalatest讨论引用(以及james moore链接到的另一个讨论)合并到两个方法中,并针对scalatest 2.x和scala 2.10进行了更新(使用classtag而不是manifest):

import org.scalatest.matchers._
import scala.reflect._

def ofType[T:ClassTag] = BeMatcher { obj: Any =>
  val cls = classTag[T].runtimeClass
  MatchResult(
    obj.getClass == cls,
    obj.toString + " was not an instance of " + cls.toString,
    obj.toString + " was an instance of " + cls.toString
  )
}

def anInstanceOf[T:ClassTag] = BeMatcher { obj: Any =>
  val cls = classTag[T].runtimeClass
  MatchResult(
    cls.isAssignableFrom(obj.getClass),
    obj.getClass.toString + " was not assignable from " + cls.toString,
    obj.getClass.toString + " was assignable from " + cls.toString
  )
}
pgx2nnw8

pgx2nnw84#

我使用2.11.8对集合进行Assert。较新的语法如下:

val scores: Map[String, Int] = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
scores shouldBe a[Map[_, _]]
lskq00tm

lskq00tm5#

scala不是java。scala没有操作符 instanceof 相反,它有一个名为 isInstanceOf[Type] .
你也可能喜欢看一个规模最大的速成班。

fnatzsnv

fnatzsnv6#

使用scalatest 2.2.x(甚至更早),您可以使用:

anInstance mustBe a[SomeClass]

相关问题