How to do an instanceof check with Scala(Test)

JavaScalaJunitScalatest

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

anInstance mustBe a[SomeClass]

Solution 3 - Java

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)

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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[_, _]] 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhelpermethodView Question on Stackoverflow
Solution 1 - JavaagilesteelView Answer on Stackoverflow
Solution 2 - Javamartin-gView Answer on Stackoverflow
Solution 3 - JavaGuillaume BelroseView Answer on Stackoverflow
Solution 4 - JavaalexbobpView Answer on Stackoverflow
Solution 5 - JavaRamanView Answer on Stackoverflow
Solution 6 - JavaaristotllView Answer on Stackoverflow