[英]How to do an instanceof check with Scala(Test)
I'm trying to incorporate ScalaTest into my Java project;我正在尝试将 ScalaTest 合并到我的 Java 项目中; replacing all JUnit tests with ScalaTests.用 ScalaTests 替换所有 JUnit 测试。 At one point, I want to check if Guice's Injector injects the correct type.有一次,我想检查 Guice 的 Injector 是否注入了正确的类型。 In Java, I have a test like this:在 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);
}
}
But I have a problem doing the same with ScalaTest:但是我在用 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)
}
}
}
It complains that the value instanceof
is not a member of Door
/ Window
/ Roof
.它抱怨值instanceof
不是Door
/ Window
/ Roof
的成员。 Can't I use instanceof
that way in Scala?我不能在 Scala 中那样使用instanceof
吗?
Scala is not Java. Scala 不是 Java。 Scala just does not have the operator instanceof
instead it has a parametric method called isInstanceOf[Type]
. Scala 只是没有操作符instanceof
而是有一个名为isInstanceOf[Type]
的参数化方法。
You might also enjoy watching a ScalaTest Crash Course .您可能还喜欢观看ScalaTest 速成课程。
使用 Scalatest 2.2.x(可能更早),您可以使用:
anInstance mustBe a[SomeClass]
If you want to be less JUnit-esque and if you want to use ScalaTest's matchers, you can write your own property matcher that matches for type (bar type erasure).如果您想减少 JUnit 风格,并且想使用 ScalaTest 的匹配器,则可以编写自己的属性匹配器来匹配类型(条形擦除)。
I found this thread to be quite useful: http://groups.google.com/group/scalatest-users/browse_thread/thread/52b75133a5c70786/1440504527566dea?#1440504527566dea我发现这个线程非常有用: http : //groups.google.com/group/scalatest-users/browse_thread/thread/52b75133a5c70786/1440504527566dea?#1440504527566dea
You can then write assertions like:然后,您可以编写如下断言:
house.door should be (anInstanceOf[WoodenDoor])
instead of代替
assert(house.door instanceof WoodenDoor)
The current answers about isInstanceOf[Type] and junit advice are good but I want to add one thing (for people who got to this page in a non-junit-related capacity).当前关于 isInstanceOf[Type] 和 junit 建议的答案很好,但我想添加一件事(对于以非 junit 相关身份访问此页面的人)。 In many cases scala pattern matching will suit your needs.在许多情况下,scala 模式匹配将满足您的需求。 I would recommend it in those cases because it gives you the typecasting for free and leaves less room for error.在这些情况下,我会推荐它,因为它为您提供免费的类型转换,并减少出错的空间。
Example:例子:
OuterType foo = blah
foo match {
case subFoo : SubType => {
subFoo.thingSubTypeDoes // no need to cast, use match variable
}
case subFoo => {
// fallthrough code
}
}
Consolidating Guillaume's ScalaTest discussion reference (and another discussion linked to by James Moore) into two methods, updated for ScalaTest 2.x and Scala 2.10 (to use ClassTag rather than manifest):将 Guillaume 的 ScalaTest 讨论参考(以及 James Moore 链接的另一个讨论)合并为两种方法,针对 ScalaTest 2.x 和 Scala 2.10 进行了更新(使用 ClassTag 而不是清单):
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
)
}
I use 2.11.8 to do the assertion with collections.我使用 2.11.8 对集合进行断言。 The newer syntax is as follows:较新的语法如下:
val scores: Map[String, Int] = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
scores shouldBe a[Map[_, _]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.