Last active
January 24, 2022 03:39
-
-
Save oharaandrew314/b8df7924095748260a15ca68af964664 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PetService(private val pets: PetsDao, private val images: ThirdPartyImageClient) { | |
fun get(id: Long): Pet? { | |
return pets[id] | |
} | |
fun create(name: String): Pet { | |
val id = pets.create(name) | |
return pets[id] ?: throw IllegalStateException("Pet was not created") | |
} | |
fun uploadImage(petId: Long, contentType: String, content: InputStream): Pet? { | |
pets[petId] ?: return null | |
val url = images.uploadImage(contentType, content) ?: return null | |
pets.addImage(petId, url) | |
return pets[petId] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PetServiceTest { | |
private val petsDao = PetsDao.mock() | |
private val thirdPartyImageBackend = FakeThirdPartyImageBackend() | |
private val testObj = PetService( | |
pets = petsDao, | |
images = ThirdPartyImageClient(thirdPartyImageBackend) | |
) | |
@Test | |
fun `get missing pet`() { | |
testObj.get(123) shouldBe null | |
} | |
@Test | |
fun `get pet`() { | |
val id = petsDao.create("Tigger") | |
testObj.get(id) shouldBe Pet( | |
id = id, | |
name = "Tigger", | |
photoUrls = emptyList() | |
) | |
} | |
@Test | |
fun `create pet`() { | |
val result = testObj.create("Tigger") | |
result.name shouldBe "Tigger" | |
result.photoUrls.shouldBeEmpty() | |
} | |
@Test | |
fun `add image`() { | |
val id = petsDao.create("Tigger") | |
val content = "foobarbaz".toByteArray() | |
val updated = content.inputStream().use { data -> | |
testObj.uploadImage(id, "image/png", data) | |
} | |
// test service result | |
updated shouldBe Pet( | |
id = id, | |
name = "Tigger", | |
photoUrls = listOf("http://images.fake/image0") | |
) | |
// test side-effect on the pets dao | |
petsDao[id].shouldNotBeNull() | |
.photoUrls.shouldContainExactly("http://images.fake/image0") | |
// test side-effect on the image repo | |
thirdPartyImageBackend.images.shouldContainExactly( | |
ThirdPartyImageDto( | |
id = "image0", | |
url = "http://images.fake/image0", | |
contentType = "image/png", | |
size = content.size | |
) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment