1
1
import org .scalatest .flatspec .AnyFlatSpec
2
2
import org .scalatest .matchers .should .Matchers
3
3
4
+ /**
5
+ * Referential transparency is a property of programming language expressions
6
+ * which means that an expression can be replaced by
7
+ * its value without changing the program's behavior.
8
+ *
9
+ * A pure function need Referential transparency
10
+ */
4
11
class ErrorManagementExceptionSpec extends AnyFlatSpec with Matchers {
5
12
6
13
trait AccountStatus
@@ -12,39 +19,40 @@ class ErrorManagementExceptionSpec extends AnyFlatSpec with Matchers {
12
19
class AccountClosedException extends RuntimeException
13
20
14
21
case class BankAccount (availableMoney : Double , status : AccountStatus )
15
- def withDraw (amount : Double , bankAccount : BankAccount ): Unit = {
22
+ def withDraw (amount : Double , bankAccount : BankAccount ): BankAccount = {
16
23
if (amount < 0 ) {
17
24
throw new NegativeAmountException
18
25
} else if (amount > bankAccount.availableMoney) {
19
26
throw new InsufficientFundsException
20
27
}else if (bankAccount.status == Closed ){
21
28
throw new AccountClosedException
22
29
}
30
+ bankAccount.copy(availableMoney = bankAccount.availableMoney- amount)
23
31
}
24
32
25
- " Withdrawing more money than the bank account holds" should " return false " in {
33
+ " Withdrawing more money than the bank account holds" should " throw a InsufficientFundsException exception " in {
26
34
val emptyBankAccount = BankAccount (0 , Open )
27
35
assertThrows[InsufficientFundsException ] {
28
36
withDraw(amount = 20_000 , bankAccount = emptyBankAccount)
29
37
}
30
38
}
31
39
32
- " Withdrawing negative money" should " return false " in {
40
+ " Withdrawing negative money" should " throw a NegativeAmountException exception " in {
33
41
val bankAccountWithMoney = BankAccount (10_000 , Open )
34
42
assertThrows[NegativeAmountException ] {
35
43
withDraw(- 100 , bankAccountWithMoney)
36
44
}
37
45
}
38
- " Withdrawing on closed money" should " return false " in {
46
+ " Withdrawing on closed money" should " throw a AccountClosedException exception " in {
39
47
val bankAccountWithMoney = BankAccount (200 , Closed )
40
48
assertThrows[AccountClosedException ] {
41
49
withDraw(100 , bankAccountWithMoney)
42
50
}
43
51
}
44
52
45
- " withdrawing money from an adequately funded account" should " return true " in {
53
+ " withdrawing money from an adequately funded account" should " return unit " in {
46
54
val bankAccountWithMoney = BankAccount (10_000 , Open )
47
- withDraw(100 , bankAccountWithMoney) shouldBe ()
55
+ withDraw(100 , bankAccountWithMoney) shouldBe (BankAccount ( 9_900 , Open ) )
48
56
}
49
57
50
58
}
0 commit comments