매처
표현력 있는 단언을 작성합니다
매처은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
매처란 무엇인가요?
ScalaTest의 매처는 단언문을 표현력 있고 영어와 비슷한 구문으로 작성하게 해 줍니다. assert(x == 3) 대신 x shouldBe 3이라고 작성하면 읽기 쉬운 테스트와 명확한 실패 메시지를 얻을 수 있습니다.
매처 혼합하기
명세에 Matchers 트레이트를 혼합하면 DSL을 사용할 수 있습니다. 어떤 테스트 스타일과도 함께 사용할 수 있습니다.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class DemoSpec extends AnyFlatSpec with Matchers {
"A value" should "equal itself" in {
val x = 3
x shouldBe 3
}
}동등성 매처
shouldBe 또는 should equal로 동등성을 확인합니다. 둘 다 ==로 비교하지만 자연스럽게 읽힙니다.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class EqSpec extends AnyFlatSpec with Matchers {
"sum" should "be correct" in {
(2 + 2) shouldBe 4
(2 + 2) should equal (4)
}
}비교 매처
숫자 비교는 문장처럼 읽힙니다. should be >, should be <=를 사용하고, 부동 소수점 허용 오차가 있는 범위에는 be within을 사용합니다.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class CmpSpec extends AnyFlatSpec with Matchers {
"a number" should "compare" in {
7 should be > 3
7 should be <= 7
2.0 shouldBe 2.0 +- 0.01
}
}문자열 매처
문자열 매처에는 startWith, endWith, include, 그리고 fullyMatch regex를 사용한 정규식 매처가 있습니다.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class StrSpec extends AnyFlatSpec with Matchers {
"a string" should "match parts" in {
"hello world" should startWith ("hello")
"hello world" should include ("o w")
"hello world" should endWith ("world")
}
}컬렉션 매처
컬렉션을 유창하게 검사할 수 있습니다. have size, contain, contain allOf를 사용하고, 비어 있는지는 shouldBe empty로 확인합니다.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class ColSpec extends AnyFlatSpec with Matchers {
"a list" should "have expected contents" in {
List(1, 2, 3) should have size 3
List(1, 2, 3) should contain (2)
List.empty[Int] shouldBe empty
}
}불리언 및 Option 매처
참·거짓 여부와 Option의 내용을 직접 매칭할 수 있습니다. shouldBe true, shouldBe defined를 사용하고 내부 값은 should contain으로 확인합니다.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class OptSpec extends AnyFlatSpec with Matchers {
"an option" should "be inspected" in {
Some(5) shouldBe defined
Some(5) should contain (5)
None shouldBe empty
}
}매처 결합하기
and/or로 기대 조건을 결합하여 복합 단언문을 만들 수 있습니다.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class CombineSpec extends AnyFlatSpec with Matchers {
"a number" should "satisfy both" in {
7 should (be > 0 and be < 10)
}
}예외 테스트하기
an [Exception] should be thrownBy { ... } 또는 assertThrows를 사용하여 코드가 예상대로 실패하는지 확인합니다.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class ExSpec extends AnyFlatSpec with Matchers {
"dividing by zero" should "throw" in {
an [ArithmeticException] should be thrownBy (1 / 0)
}
}매처가 유용한 이유
매처는 가독성뿐 아니라 설명적인 실패 메시지도 제공합니다. List(1,2) should have size 3이 실패하면 단순히 불리언 값이 거짓이라고만 말하는 일반적인 assert와 달리, 예상 크기와 실제 크기를 알려 줍니다.
shouldBe와 should equal
둘은 거의 동일합니다. shouldBe는 더 간결하고 단순한 동등성 비교에서 메시지가 약간 더 깔끔한 반면, should equal은 고급 비교를 위해 사용자 지정 Equality 인스턴스를 지원합니다.
빠른 확인
매처에 대한 지식을 확인해 보세요.
복습
ScalaTest의 매처를 배웠습니다.
- DSL을 사용하려면
Matchers를 혼합합니다. - 동등성에는
shouldBe,should equal을 사용하고, 비교에는be >,+- tolerance을 사용합니다. - 문자열에는
startWith,include를, 컬렉션에는have size,contain을 사용합니다. - 예외에는
should be thrownBy를 사용합니다. - 매처는 명확하고 설명적인 실패 정보를 제공합니다.
자주 묻는 질문
“매처” 강의는 무료인가요?
네 — “매처” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“매처”에서 뭘 배우나요?
표현력 있는 단언을 작성합니다 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“매처” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.