如何使用 Scala(Test) 进行 instanceof 检查 [英] How to do an instanceof check with Scala(Test)

查看:18
本文介绍了如何使用 Scala(Test) 进行 instanceof 检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 ScalaTest 合并到我的 Java 项目中;用 ScalaTests 替换所有 JUnit 测试.有一次,我想检查 Guice 的 Injector 是否注入了正确的类型.在 Java 中,我有一个这样的测试:

I'm trying to incorporate ScalaTest into my Java project; replacing all JUnit tests with ScalaTests. At one point, I want to check if Guice's Injector injects the correct type. In Java, I have a test like this:

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 做同样的事情时遇到了问题:

But I have a problem doing the same with 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 的成员.我不能在 Scala 中那样使用 instanceof 吗?

It complains that the value instanceof is not a member of Door/Window/Roof. Can't I use instanceof that way in Scala?

推荐答案

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

Scala is not Java. Scala just does not have the operator instanceof instead it has a parametric method called isInstanceOf[Type].

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

这篇关于如何使用 Scala(Test) 进行 instanceof 检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆