Emil
Emil

Reputation: 173

Scala test object class matcher with inheritance

I would like to write a Scala test which checks the exact class of an object created with factory method.

class Base { }

class Derived extends Base { }

class TestSpec {
  test("test instance class") {

    val result = new Derived()

    // I want to check that result is exactly Derived type
    result should be a[Derived]
    result should not be a[Base]
  }
}

I'm looking for something to test if object returned from my factory method for specific parameters is always base class. So it would be something like this is C#:

public class Base { }
    public class Derived : Base { }

    public class Program
    {
        public static void Main(string[] args)
        {
            var baseObject = new Base();
            var derivedObject = new Derived();

            var baseResult = baseObject.GetType().IsSubclassOf(typeof(Base));
            var derivedResult = derivedObject.GetType().IsSubclassOf(typeof(Base));

            Console.WriteLine(string.Format("Base is subclass of Base: {0}\nDerived is subclass of Base: {1}", baseResult, derivedResult));
        }
    } 

Upvotes: 0

Views: 1163

Answers (2)

Franck Cussac
Franck Cussac

Reputation: 319

you can do this :

    class A{}
    class B extends A{}

    val result = new B()
    result.getClass.getName shouldEqual classOf[B].getName
    result.getClass.getName.equals(classOf[A].getName) shouldBe false

Upvotes: 2

Xavier Guihot
Xavier Guihot

Reputation: 61666

new Derived() will always be an instance of Base as it inherits from Base, which means:

new Derived().isInstanceOf[Base]

will return true.

But the opposite is false: Base won't be an instance of Derived.


Thus, to check if it's the Base class (and not the Derived class), you can use these two combined conditions:

new Base() should not be a[Derived]
new Base() shouldBe a[Base]

and to check if it's the Derived class, the following is enough:

new Derived() shouldBe a[Derived]

Upvotes: 1

Related Questions