具有继承的Scala测试对象类匹配器

时间:2018-05-15 05:56:27

标签: scala scalatest

我想编写一个Scala测试,它检查使用工厂方法创建的对象的确切类。

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

我正在寻找一些东西来测试从我的工厂方法返回的特定参数的对象是否始终是基类。所以这就是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));
        }
    } 

2 个答案:

答案 0 :(得分:1)

new Derived()将始终是Base的实例,因为它继承自Base,这意味着:

new Derived().isInstanceOf[Base]

将返回true。

但反之亦然:Base不会是Derived的实例。

因此,要检查它是Base类(而不是Derived类),您可以使用以下两个组合条件:

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

并检查它是否是Derived类,以下就足够了:

new Derived() shouldBe a[Derived]

答案 1 :(得分:1)

你可以这样做:

    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