如何使用Scala执行instanceof检查(测试)


问题内容

我正在尝试将ScalaTest合并到我的Java项目中。用ScalaTests替换所有JUnit测试。一方面,我想检查Guice的Injector是否注入正确的类型。在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在Scala中使用这种方式吗?


问题答案:

Scala不是Java。Scala只是没有运算符,instanceof而是有一个称为的参数方法isInstanceOf[Type]

您可能还喜欢观看ScalaTest速成课程