Skip to content

Commit aa068f4

Browse files
Merge pull request #1661 from yadavan88/eventually-test
Code for eventually block
2 parents 7ac7d14 + 922c6ba commit aa068f4

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung.scala.eventually
2+
3+
import org.scalatest.concurrent.Eventually
4+
import org.scalatest.concurrent.Eventually.eventually
5+
import org.scalatest.concurrent.PatienceConfiguration.{Interval, Timeout}
6+
import org.scalatest.exceptions.TestFailedDueToTimeoutException
7+
import org.scalatest.flatspec.AnyFlatSpec
8+
import org.scalatest.matchers.should.Matchers
9+
import org.scalatest.time.{Millis, Seconds, Span}
10+
11+
class AsyncOperation(waitTime: Int) {
12+
private var database: Map[String, String] = Map.empty
13+
14+
def writeToDatabase(key: String, value: String): Unit = {
15+
new Thread(() => {
16+
Thread.sleep(waitTime) // Simulate a delay in writing to the database
17+
database += (key -> value)
18+
}).start()
19+
}
20+
def readFromDatabase(key: String): Option[String] = database.get(key)
21+
}
22+
class EventuallyUnitTest extends AnyFlatSpec with Matchers with Eventually {
23+
it should "retry the save to database multiple times in eventually with default timeout" in {
24+
val op = AsyncOperation(100)
25+
op.writeToDatabase("key", "value")
26+
eventually {
27+
op.readFromDatabase("key") shouldBe Some("value")
28+
}
29+
}
30+
31+
it should "throw exception if the result is not available within the expected timeout in eventually" in {
32+
val op = AsyncOperation(300)
33+
op.writeToDatabase("key", "value")
34+
assertThrows[TestFailedDueToTimeoutException] {
35+
eventually {
36+
op.readFromDatabase("key") shouldBe Some("value")
37+
}
38+
}
39+
}
40+
41+
it should "retry with newly configured timeout value" in {
42+
given patienceConfig: PatienceConfig =
43+
PatienceConfig(
44+
timeout = scaled(Span(2, Seconds)),
45+
interval = scaled(Span(5, Millis))
46+
)
47+
val op = AsyncOperation(400)
48+
op.writeToDatabase("new-key", "value")
49+
eventually {
50+
op.readFromDatabase("new-key") shouldBe Some("value")
51+
}
52+
}
53+
54+
it should "retry with explicit timeout value" in {
55+
val op = AsyncOperation(400)
56+
op.writeToDatabase("new-key", "value")
57+
eventually(
58+
timeout = Timeout(Span(2, Seconds)),
59+
interval = Interval(Span(50, Millis))
60+
) {
61+
op.readFromDatabase("new-key") shouldBe Some("value")
62+
}
63+
}
64+
}

0 commit comments

Comments
 (0)