首页 > 解决方案 > 了解测试套件

问题描述

我正在学习 scalates,并且有一个关于套件的问题。我想测试一个

class ByteSource(val src: Array[Byte])

从逻辑上讲,我将测试用例分为以下两个:

  1. 空字节源
  2. 非空字节源

问题是将案例分成不同的套件是否正确,如下所示:

class ByteSourceTest extends FunSpec with Matchers{
    describe("empty byte source operations"){
        //...
    }

    describe("non-empty byte source operations"){
        //...
    }
}

还是FunSpec不太适合这种情况?

标签: scalatestingscalatest

解决方案


FunSpec旨在提供最小的结构,因此这里没有硬性规则。自以为是的结构的一个例子是WordSpec。我会提出的一个建议是通过使用外部来清楚地识别您的测试主题describe("A ByteSource")

class ByteSourceTest extends FunSpec with Matchers {
  describe("A ByteSource") {
    describe("when empty") {
      val byteSource = new ByteSource(new Array[Byte](0))

      it("should have size 0") {
        assert(byteSource.src.size == 0)
      }

      it("should produce NoSuchElementException when head is invoked") {
        assertThrows[NoSuchElementException] {
          byteSource.src.head
        }
      }
    }

    describe("when non-empty") {
      val byteSource = new ByteSource(new Array[Byte](10))

      it("should have size > 0") {
        assert(byteSource.src.size > 0)
      }

      it("should not produce NoSuchElementException when head is invoked") {
        noException shouldBe thrownBy {
          byteSource.src.head
        }
      }
    }
  }
}

让测试对象的输出看起来像是自然语言中的规范:

A ByteSource
  when empty
  - should have size 0
  - should produce NoSuchElementException when head is invoked
  when non-empty
  - should have size > 0
  - should not produce NoSuchElementException when head is invoked

推荐阅读