Creating a Test for the Echo Service #
This tutorial demonstrates how to test the Echo service created in the Creating a Basic Custom Service topic.
This tutorial uses Pragma Engine 0.4.0.
Generate the test #
- Open your
EchoService.kt
file in IntelliJ. - Click within the parameters of 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 at
pragma-engine/platform/<PROJECT>/<PROJECT>-lib/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. Import classes as necessary.
@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. Import classes as necessary.
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.