Skip to content

Commit 5b415dd

Browse files
committed
update : split test
1 parent d6c05fd commit 5b415dd

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

core-kotlin-modules/core-kotlin-10/src/test/kotlin/com/baeldung/variableshadowing/VariableShadowingUnitTest.kt

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test
88
class VariableShadowingUnitTest{
99

1010
@Test
11-
fun `test variable shadowing`() {
11+
fun `Top-level variable shadowing`(){
1212
val number = 10 // Top-level variable
1313

1414
fun upNumber() : Int { // top-level function
@@ -18,8 +18,10 @@ class VariableShadowingUnitTest{
1818

1919
assertEquals(20, upNumber())
2020
assertEquals(10, number)
21+
}
2122

22-
// shadowing class member
23+
@Test
24+
fun `shadowing class member`(){
2325
class Car {
2426
val speed: Int = 100
2527

@@ -31,8 +33,10 @@ class VariableShadowingUnitTest{
3133

3234
assertEquals(100, Car().speed)
3335
assertEquals(200, Car().upSpeed())
36+
}
3437

35-
38+
@Test
39+
fun `local variable shadowing`(){
3640
fun calculateTotalPrice(discount: Int) {
3741
val discount = discount + 10 // Shadowing the parameter 'discount'
3842
assertEquals(30, discount)
@@ -49,16 +53,23 @@ class VariableShadowingUnitTest{
4953
}
5054

5155
calculateTotalPrice(20)
56+
}
57+
5258

59+
@Test
60+
fun `shadowing in loop`(){
5361
val numbers = listOf(1, 2, 3, 4, 5)
5462

5563
// shadowing in loop
5664
for (number in numbers) {
5765
val number = number * 2 // Shadowing the loop variable 'number'
5866
}
67+
}
5968

69+
@Test
70+
fun `shadowing in extension`(){
71+
val numbers = listOf(1, 2, 3, 4, 5)
6072

61-
// shadowing in extension
6273
assertEquals(15, numbers.sum())
6374

6475
fun List<Int>.sum(): Int { // shadowing built-in function sum()
@@ -68,8 +79,12 @@ class VariableShadowingUnitTest{
6879
}
6980

7081
assertEquals(30, numbers.sum())
82+
}
83+
84+
@Test
85+
fun `shadowing in lambda`(){
86+
val numbers = listOf(1, 2, 3, 4, 5)
7187

72-
// shadowing in lambda
7388
var sum = 0
7489

7590
numbers.forEach { number ->
@@ -84,6 +99,7 @@ class VariableShadowingUnitTest{
8499
}
85100
}
86101

102+
87103
@Test
88104
fun `solution to avoid shadowing`(){
89105
val topLevelNumber = 10 // Top-level variable
@@ -121,11 +137,6 @@ class VariableShadowingUnitTest{
121137
val price = 100 // local variable
122138
val discountRate = 0.1
123139

124-
// fun applyDiscount(price: Int): Double {
125-
// val innerDiscountRate = 0.2
126-
// return price * (1 - discountRate)
127-
// }
128-
129140
fun applyDiscount(price: Int): Double {
130141
return price * (1 - discountRate) // Use the outer discountRate directly
131142
}

0 commit comments

Comments
 (0)