Logo
Section 1 / 5

我们为什么需要模拟(Mocks)?

了解不同类型的测试替身及其使用方法。

导入

我们为什么需要模拟(Mocks)?

了解不同类型的测试替身及其使用方法。

1sealed trait Course: 2 val title: String 3 val author: Author 4 val lessons: Set[Lesson] 5 val tags: Set[String] 6 7 val price: BigDecimal 8 9 val published: Boolean 10 11 require(lessons.nonEmpty || !published, "课程只有在至少包含一个课时的情况下才能发布") 12 13 def copy( 14 title: String = title, 15 author: Author = author, 16 lessons: Set[Lesson] = lessons, 17 tags: Set[String] = tags, 18 published: Boolean = published 19 ): Course 20 21case class FreeCourse( 22 override val title: String, 23 override val author: Author, 24 override val lessons: Set[Lesson], 25 override val tags: Set[String], 26 override val published: Boolean 27 ) extends Course: 28 override val price: BigDecimal = ??? // 如前所述 29 30case class PaidCourse( 31 override val title: String, 32 override val author: Author, 33 override val lessons: Set[Lesson], 34 override val tags: Set[String], 35 override val published: Boolean 36 ) extends Course: 37 override val price: BigDecimal = ??? // 如前所述 38 39class Educative(val courses: Seq[Course]): 40 // Educative 的其余部分如前所述 41 42 def publishCourse(title: String): Educative = Educative(courses map { c => 43 if c.title == title && c.lessons.nonEmpty && !c.published then c.copy(published = true) 44 else c 45 })
1 class CourseDouble( 2 t: String, 3 ls: Set[Lesson], 4 pub: Boolean 5 ) extends Course: 6 var titleInvoked = false 7 var lessonsInvoked = false 8 var publishedInvoked = false 9 var copyInvoked = false 10 11 override def title: String = 12 titleInvoked = true 13 t 14 15 override def lessons: Set[Lesson] = 16 lessonsInvoked = true 17 ls 18 19 override def published: Boolean = 20 publishedInvoked = true 21 pub 22 23 def copy( 24 title: String, 25 author: Author, 26 lessons: Set[Lesson], 27 tags: Set[String], 28 published: Boolean 29 ): CourseDouble = 30 val newCourse = CourseDouble(t, ls, published) 31 32 newCourse.titleInvoked = titleInvoked 33 newCourse.lessonsInvoked = lessonsInvoked 34 newCourse.publishedInvoked = publishedInvoked 35 newCourse.copyInvoked = true 36 37 newCourse 38 39 override def author: Author = Author("未", "使用") 40 override def tags: Set[String] = Set.empty 41 override def price: BigDecimal = 0
1trait Course: 2 def title: String 3 val author: Author 4 def lessons: Set[Lesson] 5 val tags: Set[String] 6 7 val price: BigDecimal 8 9 def published: Boolean 10 11 // Course 的其余部分如前所述

Scala 和 sbt 简介

认识 Mockito