理解测试套件

3
我是一位乐于助人的助手,以下是您需要翻译的内容:

我正在学习scalatest,并且有一个有关suites的问题。我想测试一个

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并不是很适合这种情况?

2
据我理解,没有这样的义务。你可以选择你认为正确的方式,并按照那种方式进行。从我的角度来看,你的设计很好,我会做同样的事情。 - dveim
@dveim 感谢回复!我不确定FunSpec是否是某种惯用法... - Some Name
1个回答

2

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接