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

发布于 2024-12-22 01:04:07 字数 1150 浏览 1 评论 0原文

我正在尝试将 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/窗户/屋顶。我不能在 Scala 中使用 instanceof 吗?

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);
    }
}

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)
        }
    }
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

星光不落少年眉 2024-12-29 01:04:08

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

anInstance mustBe a[SomeClass]

With Scalatest 2.2.x (maybe even earlier) you can use:

anInstance mustBe a[SomeClass]
琉璃繁缕 2024-12-29 01:04:08

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

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

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

You might also enjoy watching a ScalaTest Crash Course.

小傻瓜 2024-12-29 01:04:08

如果您不想像 JUnit 那样,并且想使用 ScalaTest 的匹配器,则可以编写自己的属性匹配器来匹配类型(条形类型擦除)。

我发现这个线程非常有用:http://groups.google.com/group/scalatest-users/browse_thread/thread/52b75133a5c70786/1440504527566dea?#1440504527566dea

然后您可以编写如下断言:

house.door should be (anInstanceOf[WoodenDoor])

而不是

assert(house.door instanceof WoodenDoor)

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).

I found this thread to be quite useful: 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)
思慕 2024-12-29 01:04:08

当前关于 isInstanceOf[Type] 和 junit 建议的答案很好,但我想添加一件事(对于以非 junit 相关身份访问此页面的人)。在许多情况下,scala 模式匹配将满足您的需求。在这些情况下我会推荐它,因为它可以免费为您提供类型转换,并且减少出错的空间。

例子:

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

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). In many cases scala pattern matching will suit your needs. 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
  }
}
焚却相思 2024-12-29 01:04:08

将 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
  )
}

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):

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
  )
}
空城之時有危險 2024-12-29 01:04:08

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

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

I use 2.11.8 to do the assertion with collections. The newer syntax is as follows:

val scores: Map[String, Int] = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
scores shouldBe a[Map[_, _]] 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文