代码之家  ›  专栏  ›  技术社区  ›  Some Name

了解测试套件

  •  3
  • Some Name  · 技术社区  · 7 年前

    我正在学习scalatest,有一个关于套房的问题。我想测试

    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 不太适合这种情况吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Mario Galic    7 年前

    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
    
    推荐文章