Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有继承的Scala测试对象类匹配器_Scala_Scalatest - Fatal编程技术网

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

带有继承的Scala测试对象类匹配器,scala,scalatest,Scala,Scalatest,我想写一个Scala测试,它检查用factory方法创建的对象的确切类 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[De

我想写一个Scala测试,它检查用factory方法创建的对象的确切类

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

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

new Derived().isInstanceOf[Base]
将返回真值

但相反的情况是错误的:
Base
不会是
派生的
的实例


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

new Base() should not be a[Derived]
new Base() shouldBe a[Base]
要检查它是否是
派生的
类,以下内容就足够了:

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

new Derived().isInstanceOf[Base]
将返回真值

但相反的情况是错误的:
Base
不会是
派生的
的实例


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

new Base() should not be a[Derived]
new Base() shouldBe a[Base]
要检查它是否是
派生的
类,以下内容就足够了:

new Derived() shouldBe a[Derived]
您可以这样做:

    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
您可以这样做:

    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

我是斯卡拉的新手。我在Matchers上发现的只有a[T]和a[T],但它们并不像我预期的那样工作。我在这里找不到答案。您可能可以比较
obj.getClass
,但由于类型擦除,它不会考虑类型参数。(
List[String]
List[List[Int]]
擦除后是一样的,好吧)。我是scala新手。我在Matchers上发现的只有a[T]和a[T],但它们并不像我预期的那样工作。我在这里找不到答案。您可能可以比较
obj.getClass
,但由于类型擦除,它不会考虑类型参数。(
List[String]
List[List[Int]]
在擦除后是一样的,好的)。你能看看我更新的任务描述吗。我可以在不检查类名的情况下获得类是否为子类的信息吗?如果可能的话,我不知道如何获取,对不起。请查看我更新的任务描述。我能在不检查类名的情况下得到类是否是子类的信息吗?如果可能的话,我不知道怎么做,对不起。