如何使用Scala进行instanceof检查(测试) [英] How to do an instanceof check with Scala(Test)
问题描述
我正在尝试将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
不是的成员门
/ 窗口
/ 车顶
。我不能在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进行instanceof检查(测试)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!