Skip to content

Instantly share code, notes, and snippets.

@aartikov
Created November 14, 2019 05:40
Show Gist options
  • Save aartikov/f7c1987a21a0b750ab5546d1d8ffa234 to your computer and use it in GitHub Desktop.
Save aartikov/f7c1987a21a0b750ab5546d1d8ffa234 to your computer and use it in GitHub Desktop.
Pact Sample
package me.aartikov.packtest
import au.com.dius.pact.consumer.ConsumerPactTestMk2
import au.com.dius.pact.consumer.MockServer
import au.com.dius.pact.consumer.dsl.PactDslJsonBody
import au.com.dius.pact.consumer.dsl.PactDslWithProvider
import au.com.dius.pact.model.RequestResponsePact
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import org.junit.Assert
data class User(val firstName: String, val lastName: String, val age: Int)
class UserService(private val baseUrl: String) {
fun getUser(): User {
val client = OkHttpClient()
val request = Request.Builder()
.url("$baseUrl/user")
.build()
client.newCall(request).execute().use {
val response = it.body()?.string().orEmpty()
return Gson().fromJson(response, User::class.java)
}
}
}
class GetUserContractTest : ConsumerPactTestMk2() {
override fun providerName(): String = "IngoMobile Service"
override fun consumerName(): String = "IngoMobile Android"
override fun createPact(builder: PactDslWithProvider): RequestResponsePact {
val body = PactDslJsonBody()
.stringType("firstName", "John")
.stringType("lastName", "Smith")
.integerType("age", 37)
return builder.uponReceiving("Get user")
.path("/user")
.method("GET")
.willRespondWith()
.status(200)
.body(body)
.toPact()
}
override fun runTest(mockServer: MockServer) {
val userService = UserService(mockServer.getUrl())
val user = userService.getUser()
val expectedUser = User("John", "Smith", 37)
Assert.assertEquals(user, expectedUser)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment