Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.baeldung.scala.assertions

sealed trait Currency
case object USD extends Currency
case object EUR extends Currency

case class CurrencyAmount[C <: Currency](amount: Double, cur: C) {
def +(other: CurrencyAmount[C]): CurrencyAmount[C] =
CurrencyAmount(this.amount + other.amount, this.cur)
}

object Currency {
implicit class RichDouble(value: Double) {
def usd: CurrencyAmount[USD.type] = CurrencyAmount(value, USD)
def eur: CurrencyAmount[EUR.type] = CurrencyAmount(value, EUR)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.baeldung.scala.assertions

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.exceptions.TestFailedException

class AssertionsTests extends AnyFlatSpec with Matchers {

def parseAge(ageString: String): Int = {
if (ageString.isEmpty)
throw new IllegalArgumentException(
"Cannot convert and empty String to an age"
)
val age = ageString.toInt
if (age < 0) throw new IllegalArgumentException("Age cannot be negative")
age
}

"An assert" should "pass when the condition is true" in {
val sum = 1 + 1
assert(sum == 2)
}

"assertResult" should "pass when the code block produces the expected value" in {
assertResult(7) {
val sum = 3 + 4
sum
}
}

"assertThrows" should "pass when the correct exception type is thrown" in {
assertThrows[IllegalArgumentException] {
parseAge("-5")
}
}

"withClue" should "provide additional information in case of test failure" in {
withClue(
"Parsing an empty input should throw an IllegalArgumentException: "
) {
try {
parseAge("")
} catch {
case e: IllegalArgumentException =>
assert(
e.getMessage().equals("Cannot convert and empty String to an age")
)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.baeldung.scala.assertions

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class CurrencyTests extends AnyFlatSpec with Matchers {
import Currency.RichDouble

"Currency DSL" should "allow adding amounts of the same currency" in {
val a = 80.0.usd
val b = 70.0.usd
(a + b) should be(150.0.usd)
}

it should "not compile when trying to add different currencies" in {
assertDoesNotCompile("50.0.usd + 100.0.eur")
}

it should "not compile due to a type error when adding different currencies" in {
assertTypeError("50.usd + 100.eur")
}
}