Creating a Test for the Echo Service #
Generate the test #
- Open
5-ext/ext/src/main/kotlin/demo/echo/EchoService.kt
in IntelliJ. - Click within the
EchoService
class, and then right click and select Generate… and then Test…. - In the Create Test dialog window, confirm that the Class name is
EchoServiceTest
, the Destination package isdemo.echo
, and check the box next toechoV1
. - Click OK to generate a test file in
5-ext/ext/src/test/kotlin/demo/echo/EchoServiceTest.kt
.
Create the initial Echo service test structure #
- Open the
EchoServiceTest.kt
file that was created in the previous section. - Add the following code into the existing generated file, and check out the detailed explanation to understand what each section does.
package demo.echo
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import pragma.PragmaCoreTestFactory
import pragma.ProtoTestFactory
import pragma.SessionTestFactory.playerSession
@ExperimentalCoroutinesApi
internal class EchoServiceTest {
private val pragmaNode = PragmaCoreTestFactory.pragmaNode()
private val serviceInstanceId = ProtoTestFactory.serviceInstanceId(0)
val testObj = EchoService(pragmaNode, serviceInstanceId)
@Test
fun echoV1() = runTest {
val playerSession = playerSession()
}
}
Create the Echo TestFactory file #
- Create a new Kotlin file in the same directory as
EchoServiceTest.kt
calledEchoTestFactory.kt
. - Add the following code into the existing generated file, and check out the detailed explanation to understand what each section does.
package demo.echo
object EchoTestFactory {
fun echoV1Request(i: Int): EchoRpc.EchoV1Request =
EchoRpc.EchoV1Request.newBuilder().setMessage("message$i").build()
fun echoV1Response(i: Int): EchoRpc.EchoV1Response =
EchoRpc.EchoV1Response.newBuilder()
.setResponseMessage("response: message$i")
.build()
}
Add the Echo TestFactory to the Echo service test #
- Return to the
EchoServiceTest.kt
file, and add the request and response Echo TestFactory imports.
import demo.echo.EchoTestFactory.echoV1Request
import demo.echo.EchoTestFactory.echoV1Response
- Update the
@Test
with the following code, which adds our request, and then lists the trigger and expectation.
@Test
fun `echoV1 returns the correct message`() = runTest {
val playerSession = playerSession(1)
val request = echoV1Request(1)
val actualResponse = testObj.echoV1(playerSession, request)
val expectedResponse = echoV1Response(1)
assertEquals(expectedResponse, actualResponse)
}
Run the Echo service test #
- In IntelliJ, right click on
EchoServiceTest
on the left sidebar. - Select Run ‘EchoServiceTest’ and confirm that the test passes and the build is successfully completed.
Appendix #
You can view the completed source code files for this section here.