Major code refactoring

Main goals are:
1. Ability to use mocks in unit tests instead of
having to setup mock web server as if it was an
integration test.
2. Cache Retrofit services in memory
3. Make it easier to read
4. Use OptIn where possible instead of propagating
Experimental* annotations everywhere
This commit is contained in:
Kirill Kamakin
2022-04-02 19:04:44 +05:00
parent 405d983a90
commit 7fc2887dc7
40 changed files with 533 additions and 676 deletions

View File

@@ -1,84 +1,86 @@
package gq.kirmanak.mealient.data.auth.impl
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.data.auth.impl.AuthenticationError.*
import gq.kirmanak.mealient.data.network.ServiceFactory
import gq.kirmanak.mealient.di.AppModule
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_BASE_URL
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_PASSWORD
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_TOKEN
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_USERNAME
import gq.kirmanak.mealient.test.AuthImplTestData.body
import gq.kirmanak.mealient.test.AuthImplTestData.enqueueSuccessfulAuthResponse
import gq.kirmanak.mealient.test.AuthImplTestData.enqueueUnsuccessfulAuthResponse
import gq.kirmanak.mealient.test.MockServerTest
import gq.kirmanak.mealient.test.toJsonResponseBody
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.every
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.ExperimentalSerializationApi
import okhttp3.mockwebserver.MockResponse
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import javax.inject.Inject
import retrofit2.Response
import java.io.IOException
@OptIn(ExperimentalCoroutinesApi::class)
class AuthDataSourceImplTest {
@MockK
lateinit var authService: AuthService
@MockK
lateinit var authServiceFactory: ServiceFactory<AuthService>
@ExperimentalSerializationApi
@ExperimentalCoroutinesApi
@HiltAndroidTest
class AuthDataSourceImplTest : MockServerTest() {
@Inject
lateinit var subject: AuthDataSourceImpl
@Before
fun setUp() {
MockKAnnotations.init(this)
subject = AuthDataSourceImpl(authServiceFactory, AppModule.createJson())
}
@Test
fun `when authentication is successful then token is correct`() = runBlocking {
mockServer.enqueueSuccessfulAuthResponse()
val token = subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
fun `when authentication is successful then token is correct`() = runTest {
val token = authenticate(Response.success(GetTokenResponse(TEST_TOKEN)))
assertThat(token).isEqualTo(TEST_TOKEN)
}
@Test(expected = Unauthorized::class)
fun `when authentication isn't successful then throws`(): Unit = runBlocking {
mockServer.enqueueUnsuccessfulAuthResponse()
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
}
@Test
fun `when authentication is requested then body is correct`() = runBlocking {
mockServer.enqueueSuccessfulAuthResponse()
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
val body = mockServer.takeRequest().body()
assertThat(body).isEqualTo("username=$TEST_USERNAME&password=$TEST_PASSWORD")
}
@Test
fun `when authentication is requested then path is correct`() = runBlocking {
mockServer.enqueueSuccessfulAuthResponse()
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
val path = mockServer.takeRequest().path
assertThat(path).isEqualTo("/api/auth/token")
fun `when authenticate receives 401 and Unauthorized then throws Unauthorized`() = runTest {
val body = "{\"detail\":\"Unauthorized\"}".toJsonResponseBody()
authenticate(Response.error(401, body))
}
@Test(expected = NotMealie::class)
fun `when authenticate but response empty then NotMealie`(): Unit = runBlocking {
val response = MockResponse().setResponseCode(200)
mockServer.enqueue(response)
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
fun `when authenticate receives 401 but not Unauthorized then throws NotMealie`() = runTest {
val body = "{\"detail\":\"Something\"}".toJsonResponseBody()
authenticate(Response.error(401, body))
}
@Test(expected = NotMealie::class)
fun `when authenticate but response invalid then NotMealie`(): Unit = runBlocking {
val response = MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "application/json")
.setBody("{\"test\": \"test\"")
mockServer.enqueue(response)
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
fun `when authenticate receives 404 and empty body then throws NotMealie`() = runTest {
authenticate(Response.error(401, "".toJsonResponseBody()))
}
@Test(expected = NotMealie::class)
fun `when authenticate but response not found then NotMealie`(): Unit = runBlocking {
val response = MockResponse().setResponseCode(404)
mockServer.enqueue(response)
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
fun `when authenticate receives 200 and null then throws NotMealie`() = runTest {
authenticate(Response.success<GetTokenResponse>(200, null))
}
@Test(expected = NoServerConnection::class)
fun `when authenticate but host not found then NoServerConnection`(): Unit = runBlocking {
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, "http://test")
fun `when authenticate and getToken throws then throws NoServerConnection`() = runTest {
setUpAuthServiceFactory()
coEvery { authService.getToken(any(), any()) } throws IOException("Server not found")
callAuthenticate()
}
private suspend fun authenticate(response: Response<GetTokenResponse>): String {
setUpAuthServiceFactory()
coEvery { authService.getToken(eq(TEST_USERNAME), eq(TEST_PASSWORD)) } returns response
return callAuthenticate()
}
private suspend fun callAuthenticate() =
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, TEST_BASE_URL)
private fun setUpAuthServiceFactory() {
every { authServiceFactory.provideService(eq(TEST_BASE_URL)) } returns authService
}
}

View File

@@ -1,55 +1,74 @@
package gq.kirmanak.mealient.data.auth.impl
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.data.auth.AuthDataSource
import gq.kirmanak.mealient.data.auth.AuthStorage
import gq.kirmanak.mealient.data.auth.impl.AuthenticationError.MalformedUrl
import gq.kirmanak.mealient.data.auth.impl.AuthenticationError.Unauthorized
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_AUTH_HEADER
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_BASE_URL
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_PASSWORD
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_TOKEN
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_USERNAME
import gq.kirmanak.mealient.test.AuthImplTestData.enqueueSuccessfulAuthResponse
import gq.kirmanak.mealient.test.AuthImplTestData.enqueueUnsuccessfulAuthResponse
import gq.kirmanak.mealient.test.MockServerTest
import gq.kirmanak.mealient.test.RobolectricTest
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import javax.inject.Inject
@HiltAndroidTest
class AuthRepoImplTest : MockServerTest() {
@Inject
@OptIn(ExperimentalCoroutinesApi::class)
class AuthRepoImplTest : RobolectricTest() {
@MockK
lateinit var dataSource: AuthDataSource
@MockK(relaxUnitFun = true)
lateinit var storage: AuthStorage
lateinit var subject: AuthRepoImpl
@Before
fun setUp() {
MockKAnnotations.init(this)
subject = AuthRepoImpl(dataSource, storage)
}
@Test
fun `when not authenticated then first auth status is false`() = runBlocking {
fun `when not authenticated then first auth status is false`() = runTest {
coEvery { storage.authHeaderObservable() } returns flowOf(null)
assertThat(subject.authenticationStatuses().first()).isFalse()
}
@Test
fun `when authenticated then first auth status is true`() = runBlocking {
mockServer.enqueueSuccessfulAuthResponse()
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
fun `when authenticated then first auth status is true`() = runTest {
coEvery { storage.authHeaderObservable() } returns flowOf(TEST_AUTH_HEADER)
assertThat(subject.authenticationStatuses().first()).isTrue()
}
@Test(expected = Unauthorized::class)
fun `when authentication fails then authenticate throws`() = runBlocking {
mockServer.enqueueUnsuccessfulAuthResponse()
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
fun `when authentication fails then authenticate throws`() = runTest {
coEvery {
dataSource.authenticate(eq(TEST_USERNAME), eq(TEST_PASSWORD), eq(TEST_BASE_URL))
} throws Unauthorized(RuntimeException())
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, TEST_BASE_URL)
}
@Test
fun `when authenticated then getToken returns token`() = runBlocking {
mockServer.enqueueSuccessfulAuthResponse()
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
assertThat(subject.getToken()).isEqualTo(TEST_TOKEN)
fun `when authenticated then getToken returns token`() = runTest {
coEvery { storage.getAuthHeader() } returns TEST_AUTH_HEADER
assertThat(subject.getAuthHeader()).isEqualTo(TEST_AUTH_HEADER)
}
@Test
fun `when authenticated then getBaseUrl returns url`() = runBlocking {
mockServer.enqueueSuccessfulAuthResponse()
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
assertThat(subject.getBaseUrl()).isEqualTo(serverUrl)
fun `when authenticated then getBaseUrl returns url`() = runTest {
coEvery { storage.getBaseUrl() } returns TEST_BASE_URL
assertThat(subject.getBaseUrl()).isEqualTo(TEST_BASE_URL)
}
@Test(expected = MalformedUrl::class)
@@ -76,4 +95,19 @@ class AuthRepoImplTest : MockServerTest() {
fun `when baseUrl is correct then doesn't change`() {
assertThat(subject.parseBaseUrl("https://google.com/")).isEqualTo("https://google.com/")
}
@Test
fun `when authenticated successfully then stores token and url`() = runTest {
coEvery {
dataSource.authenticate(eq(TEST_USERNAME), eq(TEST_PASSWORD), eq(TEST_BASE_URL))
} returns TEST_TOKEN
subject.authenticate(TEST_USERNAME, TEST_PASSWORD, TEST_BASE_URL)
verify { storage.storeAuthData(TEST_AUTH_HEADER, TEST_BASE_URL) }
}
@Test
fun `when logout then clearAuthData is called`() = runTest {
subject.logout()
verify { storage.clearAuthData() }
}
}

View File

@@ -2,76 +2,77 @@ package gq.kirmanak.mealient.data.auth.impl
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_TOKEN
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_AUTH_HEADER
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_URL
import gq.kirmanak.mealient.test.HiltRobolectricTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Test
import javax.inject.Inject
@ExperimentalCoroutinesApi
@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
class AuthStorageImplTest : HiltRobolectricTest() {
@Inject
lateinit var subject: AuthStorageImpl
@Test
fun `when storing auth data then doesn't throw`() = runBlocking {
subject.storeAuthData(TEST_TOKEN, TEST_URL)
fun `when storing auth data then doesn't throw`() = runTest {
subject.storeAuthData(TEST_AUTH_HEADER, TEST_URL)
}
@Test
fun `when reading url after storing data then returns url`() = runBlocking {
subject.storeAuthData(TEST_TOKEN, TEST_URL)
fun `when reading url after storing data then returns url`() = runTest {
subject.storeAuthData(TEST_AUTH_HEADER, TEST_URL)
assertThat(subject.getBaseUrl()).isEqualTo(TEST_URL)
}
@Test
fun `when reading token after storing data then returns token`() = runBlocking {
subject.storeAuthData(TEST_TOKEN, TEST_URL)
assertThat(subject.getToken()).isEqualTo(TEST_TOKEN)
fun `when reading token after storing data then returns token`() = runTest {
subject.storeAuthData(TEST_AUTH_HEADER, TEST_URL)
assertThat(subject.getAuthHeader()).isEqualTo(TEST_AUTH_HEADER)
}
@Test
fun `when reading token without storing data then returns null`() = runBlocking {
assertThat(subject.getToken()).isNull()
fun `when reading token without storing data then returns null`() = runTest {
assertThat(subject.getAuthHeader()).isNull()
}
@Test
fun `when reading url without storing data then returns null`() = runBlocking {
fun `when reading url without storing data then returns null`() = runTest {
assertThat(subject.getBaseUrl()).isNull()
}
@Test
fun `when didn't store auth data then first token is null`() = runBlocking {
assertThat(subject.tokenObservable().first()).isNull()
fun `when didn't store auth data then first token is null`() = runTest {
assertThat(subject.authHeaderObservable().first()).isNull()
}
@Test
fun `when stored auth data then first token is correct`() = runBlocking {
subject.storeAuthData(TEST_TOKEN, TEST_URL)
assertThat(subject.tokenObservable().first()).isEqualTo(TEST_TOKEN)
fun `when stored auth data then first token is correct`() = runTest {
subject.storeAuthData(TEST_AUTH_HEADER, TEST_URL)
assertThat(subject.authHeaderObservable().first()).isEqualTo(TEST_AUTH_HEADER)
}
@Test
fun `when clearAuthData then first token is null`() = runBlocking {
subject.storeAuthData(TEST_TOKEN, TEST_URL)
fun `when clearAuthData then first token is null`() = runTest {
subject.storeAuthData(TEST_AUTH_HEADER, TEST_URL)
subject.clearAuthData()
assertThat(subject.tokenObservable().first()).isNull()
assertThat(subject.authHeaderObservable().first()).isNull()
}
@Test
fun `when clearAuthData then getToken returns null`() = runBlocking {
subject.storeAuthData(TEST_TOKEN, TEST_URL)
fun `when clearAuthData then getToken returns null`() = runTest {
subject.storeAuthData(TEST_AUTH_HEADER, TEST_URL)
subject.clearAuthData()
assertThat(subject.getToken()).isNull()
assertThat(subject.getAuthHeader()).isNull()
}
@Test
fun `when clearAuthData then getBaseUrl returns null`() = runBlocking {
subject.storeAuthData(TEST_TOKEN, TEST_URL)
fun `when clearAuthData then getBaseUrl returns null`() = runTest {
subject.storeAuthData(TEST_AUTH_HEADER, TEST_URL)
subject.clearAuthData()
assertThat(subject.getBaseUrl()).isNull()
}

View File

@@ -3,22 +3,24 @@ package gq.kirmanak.mealient.data.disclaimer
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.test.HiltRobolectricTest
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test
import javax.inject.Inject
@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
class DisclaimerStorageImplTest : HiltRobolectricTest() {
@Inject
lateinit var subject: DisclaimerStorageImpl
@Test
fun `when isDisclaimerAccepted initially then false`(): Unit = runBlocking {
fun `when isDisclaimerAccepted initially then false`() = runTest {
assertThat(subject.isDisclaimerAccepted()).isFalse()
}
@Test
fun `when isDisclaimerAccepted after accept then true`(): Unit = runBlocking {
fun `when isDisclaimerAccepted after accept then true`() = runTest {
subject.acceptDisclaimer()
assertThat(subject.isDisclaimerAccepted()).isTrue()
}

View File

@@ -1,46 +0,0 @@
package gq.kirmanak.mealient.data.impl
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.data.auth.AuthStorage
import gq.kirmanak.mealient.data.auth.impl.AUTHORIZATION_HEADER
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_TOKEN
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_URL
import gq.kirmanak.mealient.test.MockServerTest
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.mockwebserver.MockResponse
import org.junit.Test
import javax.inject.Inject
@HiltAndroidTest
class OkHttpBuilderTest : MockServerTest() {
@Inject
lateinit var subject: OkHttpBuilder
@Inject
lateinit var authStorage: AuthStorage
@Test
fun `when token null then no auth header`() {
val client = subject.buildOkHttp()
val header = sendRequestAndExtractAuthHeader(client)
assertThat(header).isNull()
}
@Test
fun `when token isn't null then auth header contains token`() {
authStorage.storeAuthData(TEST_TOKEN, TEST_URL)
val client = subject.buildOkHttp()
val header = sendRequestAndExtractAuthHeader(client)
assertThat(header).isEqualTo("Bearer $TEST_TOKEN")
}
private fun sendRequestAndExtractAuthHeader(client: OkHttpClient): String? {
mockServer.enqueue(MockResponse())
val request = Request.Builder().url(serverUrl).get().build()
client.newCall(request).execute()
return mockServer.takeRequest().getHeader(AUTHORIZATION_HEADER)
}
}

View File

@@ -21,11 +21,13 @@ import gq.kirmanak.mealient.test.RecipeImplTestData.PORRIDGE_RECIPE_SUMMARY_ENTI
import gq.kirmanak.mealient.test.RecipeImplTestData.RECIPE_SUMMARY_CAKE
import gq.kirmanak.mealient.test.RecipeImplTestData.RECIPE_SUMMARY_PORRIDGE
import gq.kirmanak.mealient.test.RecipeImplTestData.TEST_RECIPE_SUMMARIES
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test
import javax.inject.Inject
@HiltAndroidTest
@OptIn(ExperimentalCoroutinesApi::class)
class RecipeStorageImplTest : HiltRobolectricTest() {
@Inject
@@ -35,7 +37,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
lateinit var appDb: AppDb
@Test
fun `when saveRecipes then saves tags`(): Unit = runBlocking {
fun `when saveRecipes then saves tags`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
val actualTags = appDb.recipeDao().queryAllTags()
assertThat(actualTags).containsExactly(
@@ -46,7 +48,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when saveRecipes then saves categories`(): Unit = runBlocking {
fun `when saveRecipes then saves categories`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
val actual = appDb.recipeDao().queryAllCategories()
assertThat(actual).containsExactly(
@@ -57,7 +59,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when saveRecipes then saves recipes`(): Unit = runBlocking {
fun `when saveRecipes then saves recipes`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
val actualTags = appDb.recipeDao().queryAllRecipes()
assertThat(actualTags).containsExactly(
@@ -67,7 +69,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when saveRecipes then saves category recipes`(): Unit = runBlocking {
fun `when saveRecipes then saves category recipes`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
val actual = appDb.recipeDao().queryAllCategoryRecipes()
assertThat(actual).containsExactly(
@@ -79,7 +81,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when saveRecipes then saves tag recipes`(): Unit = runBlocking {
fun `when saveRecipes then saves tag recipes`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
val actual = appDb.recipeDao().queryAllTagRecipes()
assertThat(actual).containsExactly(
@@ -91,7 +93,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when refreshAll then old recipes aren't preserved`(): Unit = runBlocking {
fun `when refreshAll then old recipes aren't preserved`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
subject.refreshAll(listOf(RECIPE_SUMMARY_CAKE))
val actual = appDb.recipeDao().queryAllRecipes()
@@ -99,7 +101,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when refreshAll then old category recipes aren't preserved`(): Unit = runBlocking {
fun `when refreshAll then old category recipes aren't preserved`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
subject.refreshAll(listOf(RECIPE_SUMMARY_CAKE))
val actual = appDb.recipeDao().queryAllCategoryRecipes()
@@ -110,7 +112,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when refreshAll then old tag recipes aren't preserved`(): Unit = runBlocking {
fun `when refreshAll then old tag recipes aren't preserved`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
subject.refreshAll(listOf(RECIPE_SUMMARY_CAKE))
val actual = appDb.recipeDao().queryAllTagRecipes()
@@ -121,7 +123,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when clearAllLocalData then recipes aren't preserved`(): Unit = runBlocking {
fun `when clearAllLocalData then recipes aren't preserved`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
subject.clearAllLocalData()
val actual = appDb.recipeDao().queryAllRecipes()
@@ -129,7 +131,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when clearAllLocalData then categories aren't preserved`(): Unit = runBlocking {
fun `when clearAllLocalData then categories aren't preserved`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
subject.clearAllLocalData()
val actual = appDb.recipeDao().queryAllCategories()
@@ -137,7 +139,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when clearAllLocalData then tags aren't preserved`(): Unit = runBlocking {
fun `when clearAllLocalData then tags aren't preserved`() = runTest {
subject.saveRecipes(TEST_RECIPE_SUMMARIES)
subject.clearAllLocalData()
val actual = appDb.recipeDao().queryAllTags()
@@ -145,7 +147,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when saveRecipeInfo then saves recipe info`(): Unit = runBlocking {
fun `when saveRecipeInfo then saves recipe info`() = runTest {
subject.saveRecipes(listOf(RECIPE_SUMMARY_CAKE))
subject.saveRecipeInfo(GET_CAKE_RESPONSE)
val actual = appDb.recipeDao().queryFullRecipeInfo(1)
@@ -153,7 +155,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when saveRecipeInfo with two then saves second`(): Unit = runBlocking {
fun `when saveRecipeInfo with two then saves second`() = runTest {
subject.saveRecipes(listOf(RECIPE_SUMMARY_CAKE, RECIPE_SUMMARY_PORRIDGE))
subject.saveRecipeInfo(GET_CAKE_RESPONSE)
subject.saveRecipeInfo(GET_PORRIDGE_RESPONSE)
@@ -162,7 +164,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when saveRecipeInfo secondly then overwrites ingredients`(): Unit = runBlocking {
fun `when saveRecipeInfo secondly then overwrites ingredients`() = runTest {
subject.saveRecipes(listOf(RECIPE_SUMMARY_CAKE))
subject.saveRecipeInfo(GET_CAKE_RESPONSE)
val newRecipe = GET_CAKE_RESPONSE.copy(recipeIngredients = listOf(BREAD_INGREDIENT))
@@ -173,7 +175,7 @@ class RecipeStorageImplTest : HiltRobolectricTest() {
}
@Test
fun `when saveRecipeInfo secondly then overwrites instructions`(): Unit = runBlocking {
fun `when saveRecipeInfo secondly then overwrites instructions`() = runTest {
subject.saveRecipes(listOf(RECIPE_SUMMARY_CAKE))
subject.saveRecipeInfo(GET_CAKE_RESPONSE)
val newRecipe = GET_CAKE_RESPONSE.copy(recipeInstructions = listOf(MIX_INSTRUCTION))

View File

@@ -1,74 +1,80 @@
package gq.kirmanak.mealient.data.recipes.impl
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.data.auth.AuthStorage
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_TOKEN
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_URL
import gq.kirmanak.mealient.test.HiltRobolectricTest
import kotlinx.coroutines.runBlocking
import gq.kirmanak.mealient.data.auth.AuthRepo
import gq.kirmanak.mealient.ui.ImageLoader
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import javax.inject.Inject
@HiltAndroidTest
class RecipeImageLoaderImplTest : HiltRobolectricTest() {
@Inject
@OptIn(ExperimentalCoroutinesApi::class)
class RecipeImageLoaderImplTest {
lateinit var subject: RecipeImageLoaderImpl
@Inject
lateinit var authStorage: AuthStorage
@MockK
lateinit var authRepo: AuthRepo
@MockK
lateinit var imageLoader: ImageLoader
@Before
fun setUp() {
MockKAnnotations.init(this)
subject = RecipeImageLoaderImpl(imageLoader, authRepo)
coEvery { authRepo.getBaseUrl() } returns "https://google.com/"
}
@Test
fun `when url has slash then generated doesn't add new`() = runBlocking {
authStorage.storeAuthData(TEST_TOKEN, "https://google.com/")
fun `when url has slash then generated doesn't add new`() = runTest {
val actual = subject.generateImageUrl("cake")
assertThat(actual).isEqualTo("https://google.com/api/media/recipes/cake/images/original.webp")
}
@Test
fun `when url doesn't have slash then generated adds new`() = runBlocking {
authStorage.storeAuthData(TEST_TOKEN, "https://google.com")
fun `when url doesn't have slash then generated adds new`() = runTest {
val actual = subject.generateImageUrl("cake")
assertThat(actual).isEqualTo("https://google.com/api/media/recipes/cake/images/original.webp")
}
@Test
fun `when url is null then generated is null`() = runBlocking {
fun `when url is null then generated is null`() = runTest {
coEvery { authRepo.getBaseUrl() } returns null
val actual = subject.generateImageUrl("cake")
assertThat(actual).isNull()
}
@Test
fun `when url is blank then generated is null`() = runBlocking {
authStorage.storeAuthData(TEST_TOKEN, " ")
fun `when url is blank then generated is null`() = runTest {
coEvery { authRepo.getBaseUrl() } returns " "
val actual = subject.generateImageUrl("cake")
assertThat(actual).isNull()
}
@Test
fun `when url is empty then generated is null`() = runBlocking {
authStorage.storeAuthData(TEST_TOKEN, "")
fun `when url is empty then generated is null`() = runTest {
coEvery { authRepo.getBaseUrl() } returns ""
val actual = subject.generateImageUrl("cake")
assertThat(actual).isNull()
}
@Test
fun `when slug is empty then generated is null`() = runBlocking {
authStorage.storeAuthData(TEST_TOKEN, TEST_URL)
fun `when slug is empty then generated is null`() = runTest {
val actual = subject.generateImageUrl("")
assertThat(actual).isNull()
}
@Test
fun `when slug is blank then generated is null`() = runBlocking {
authStorage.storeAuthData(TEST_TOKEN, TEST_URL)
fun `when slug is blank then generated is null`() = runTest {
val actual = subject.generateImageUrl(" ")
assertThat(actual).isNull()
}
@Test
fun `when slug is null then generated is null`() = runBlocking {
authStorage.storeAuthData(TEST_TOKEN, TEST_URL)
fun `when slug is null then generated is null`() = runTest {
val actual = subject.generateImageUrl(null)
assertThat(actual).isNull()
}

View File

@@ -1,53 +1,65 @@
package gq.kirmanak.mealient.data.recipes.impl
import androidx.paging.InvalidatingPagingSourceFactory
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.data.AppDb
import gq.kirmanak.mealient.data.recipes.RecipeRepo
import gq.kirmanak.mealient.data.recipes.db.RecipeStorage
import gq.kirmanak.mealient.test.MockServerWithAuthTest
import gq.kirmanak.mealient.data.recipes.db.entity.RecipeSummaryEntity
import gq.kirmanak.mealient.data.recipes.network.RecipeDataSource
import gq.kirmanak.mealient.test.RecipeImplTestData.FULL_CAKE_INFO_ENTITY
import gq.kirmanak.mealient.test.RecipeImplTestData.RECIPE_SUMMARY_CAKE
import gq.kirmanak.mealient.test.RecipeImplTestData.enqueueSuccessfulGetRecipe
import gq.kirmanak.mealient.test.RecipeImplTestData.enqueueUnsuccessfulRecipeResponse
import kotlinx.coroutines.runBlocking
import gq.kirmanak.mealient.test.RecipeImplTestData.GET_CAKE_RESPONSE
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import javax.inject.Inject
@HiltAndroidTest
class RecipeRepoImplTest : MockServerWithAuthTest() {
@Inject
lateinit var subject: RecipeRepo
@OptIn(ExperimentalCoroutinesApi::class)
class RecipeRepoImplTest {
@Inject
@MockK(relaxUnitFun = true)
lateinit var storage: RecipeStorage
@Inject
lateinit var appDb: AppDb
@MockK
lateinit var dataSource: RecipeDataSource
@MockK
lateinit var remoteMediator: RecipesRemoteMediator
@MockK
lateinit var pagingSourceFactory: InvalidatingPagingSourceFactory<Int, RecipeSummaryEntity>
lateinit var subject: RecipeRepo
@Before
fun setUp() {
MockKAnnotations.init(this)
subject = RecipeRepoImpl(remoteMediator, storage, pagingSourceFactory, dataSource)
}
@Test
fun `when loadRecipeInfo then loads recipe`(): Unit = runBlocking {
storage.saveRecipes(listOf(RECIPE_SUMMARY_CAKE))
mockServer.enqueueSuccessfulGetRecipe()
fun `when loadRecipeInfo then loads recipe`() = runTest {
coEvery { dataSource.requestRecipeInfo(eq("cake")) } returns GET_CAKE_RESPONSE
coEvery { storage.queryRecipeInfo(eq(1)) } returns FULL_CAKE_INFO_ENTITY
val actual = subject.loadRecipeInfo(1, "cake")
assertThat(actual).isEqualTo(FULL_CAKE_INFO_ENTITY)
}
@Test
fun `when loadRecipeInfo then saves to DB`(): Unit = runBlocking {
storage.saveRecipes(listOf(RECIPE_SUMMARY_CAKE))
mockServer.enqueueSuccessfulGetRecipe()
fun `when loadRecipeInfo then saves to DB`() = runTest {
coEvery { dataSource.requestRecipeInfo(eq("cake")) } returns GET_CAKE_RESPONSE
coEvery { storage.queryRecipeInfo(eq(1)) } returns FULL_CAKE_INFO_ENTITY
subject.loadRecipeInfo(1, "cake")
val actual = appDb.recipeDao().queryFullRecipeInfo(1)
assertThat(actual).isEqualTo(FULL_CAKE_INFO_ENTITY)
coVerify { storage.saveRecipeInfo(eq(GET_CAKE_RESPONSE)) }
}
@Test
fun `when loadRecipeInfo with error then loads from DB`(): Unit = runBlocking {
storage.saveRecipes(listOf(RECIPE_SUMMARY_CAKE))
mockServer.enqueueSuccessfulGetRecipe()
subject.loadRecipeInfo(1, "cake")
mockServer.enqueueUnsuccessfulRecipeResponse()
fun `when loadRecipeInfo with error then loads from DB`() = runTest {
coEvery { dataSource.requestRecipeInfo(eq("cake")) } throws RuntimeException()
coEvery { storage.queryRecipeInfo(eq(1)) } returns FULL_CAKE_INFO_ENTITY
val actual = subject.loadRecipeInfo(1, "cake")
assertThat(actual).isEqualTo(FULL_CAKE_INFO_ENTITY)
}

View File

@@ -3,115 +3,137 @@ package gq.kirmanak.mealient.data.recipes.impl
import androidx.paging.*
import androidx.paging.LoadType.*
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.data.AppDb
import gq.kirmanak.mealient.data.auth.impl.AuthenticationError.Unauthorized
import gq.kirmanak.mealient.data.recipes.db.RecipeStorage
import gq.kirmanak.mealient.data.recipes.db.entity.RecipeSummaryEntity
import gq.kirmanak.mealient.test.MockServerWithAuthTest
import gq.kirmanak.mealient.test.RecipeImplTestData.CAKE_RECIPE_SUMMARY_ENTITY
import gq.kirmanak.mealient.test.RecipeImplTestData.PORRIDGE_RECIPE_SUMMARY_ENTITY
import gq.kirmanak.mealient.test.RecipeImplTestData.TEST_RECIPE_ENTITIES
import gq.kirmanak.mealient.test.RecipeImplTestData.enqueueSuccessfulRecipeSummaryResponse
import gq.kirmanak.mealient.test.RecipeImplTestData.enqueueUnsuccessfulRecipeResponse
import kotlinx.coroutines.runBlocking
import gq.kirmanak.mealient.data.recipes.network.RecipeDataSource
import gq.kirmanak.mealient.test.RecipeImplTestData.TEST_RECIPE_SUMMARIES
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import javax.inject.Inject
@ExperimentalPagingApi
@HiltAndroidTest
class RecipesRemoteMediatorTest : MockServerWithAuthTest() {
@ExperimentalCoroutinesApi
@OptIn(ExperimentalPagingApi::class)
class RecipesRemoteMediatorTest {
private val pagingConfig = PagingConfig(
pageSize = 2,
prefetchDistance = 5,
enablePlaceholders = false
)
@Inject
lateinit var subject: RecipesRemoteMediator
@Inject
lateinit var appDb: AppDb
@MockK(relaxUnitFun = true)
lateinit var storage: RecipeStorage
@MockK
lateinit var dataSource: RecipeDataSource
@MockK(relaxUnitFun = true)
lateinit var pagingSourceFactory: InvalidatingPagingSourceFactory<Int, RecipeSummaryEntity>
@Before
fun setUp() {
MockKAnnotations.init(this)
subject = RecipesRemoteMediator(storage, dataSource, pagingSourceFactory)
}
@Test
fun `when first load with refresh successful then result success`(): Unit = runBlocking {
mockServer.enqueueSuccessfulRecipeSummaryResponse()
fun `when first load with refresh successful then result success`() = runTest {
coEvery { dataSource.requestRecipes(eq(0), eq(6)) } returns TEST_RECIPE_SUMMARIES
val result = subject.load(REFRESH, pagingState())
assertThat(result).isInstanceOf(RemoteMediator.MediatorResult.Success::class.java)
}
@Test
fun `when first load with refresh successful then recipes stored`(): Unit = runBlocking {
mockServer.enqueueSuccessfulRecipeSummaryResponse()
subject.load(REFRESH, pagingState())
val actual = appDb.recipeDao().queryAllRecipes()
assertThat(actual).containsExactly(
CAKE_RECIPE_SUMMARY_ENTITY,
PORRIDGE_RECIPE_SUMMARY_ENTITY
)
fun `when first load with refresh successful then end is reached`() = runTest {
coEvery { dataSource.requestRecipes(eq(0), eq(6)) } returns TEST_RECIPE_SUMMARIES
val result = subject.load(REFRESH, pagingState())
assertThat((result as RemoteMediator.MediatorResult.Success).endOfPaginationReached).isTrue()
}
@Test
fun `when load state prepend then success`(): Unit = runBlocking {
fun `when first load with refresh successful then invalidate called`() = runTest {
coEvery { dataSource.requestRecipes(any(), any()) } returns TEST_RECIPE_SUMMARIES
subject.load(REFRESH, pagingState())
verify { pagingSourceFactory.invalidate() }
}
@Test
fun `when first load with refresh successful then recipes stored`() = runTest {
coEvery { dataSource.requestRecipes(eq(0), eq(6)) } returns TEST_RECIPE_SUMMARIES
subject.load(REFRESH, pagingState())
coVerify { storage.refreshAll(eq(TEST_RECIPE_SUMMARIES)) }
}
@Test
fun `when load state prepend then success`() = runTest {
val result = subject.load(PREPEND, pagingState())
assertThat(result).isInstanceOf(RemoteMediator.MediatorResult.Success::class.java)
}
@Test
fun `when load state prepend then end is reached`(): Unit = runBlocking {
fun `when load state prepend then end is reached`() = runTest {
val result = subject.load(PREPEND, pagingState())
assertThat((result as RemoteMediator.MediatorResult.Success).endOfPaginationReached).isTrue()
}
@Test
fun `when load successful then lastRequestEnd updated`(): Unit = runBlocking {
mockServer.enqueueSuccessfulRecipeSummaryResponse()
fun `when load successful then lastRequestEnd updated`() = runTest {
coEvery { dataSource.requestRecipes(eq(0), eq(6)) } returns TEST_RECIPE_SUMMARIES
subject.load(REFRESH, pagingState())
val actual = subject.lastRequestEnd
assertThat(actual).isEqualTo(2)
}
@Test
fun `when load fails then lastRequestEnd still 0`(): Unit = runBlocking {
mockServer.enqueueUnsuccessfulRecipeResponse()
fun `when load fails then lastRequestEnd still 0`() = runTest {
coEvery { dataSource.requestRecipes(eq(0), eq(6)) } throws Unauthorized(RuntimeException())
subject.load(REFRESH, pagingState())
val actual = subject.lastRequestEnd
assertThat(actual).isEqualTo(0)
}
@Test
fun `when load fails then result is error`(): Unit = runBlocking {
mockServer.enqueueUnsuccessfulRecipeResponse()
fun `when load fails then result is error`() = runTest {
coEvery { dataSource.requestRecipes(eq(0), eq(6)) } throws Unauthorized(RuntimeException())
val actual = subject.load(REFRESH, pagingState())
assertThat(actual).isInstanceOf(RemoteMediator.MediatorResult.Error::class.java)
}
@Test
fun `when refresh then request params correct`(): Unit = runBlocking {
mockServer.enqueueUnsuccessfulRecipeResponse()
fun `when refresh then request params correct`() = runTest {
coEvery { dataSource.requestRecipes(any(), any()) } throws Unauthorized(RuntimeException())
subject.load(REFRESH, pagingState())
val actual = mockServer.takeRequest().path
assertThat(actual).isEqualTo("/api/recipes/summary?start=0&limit=6")
coVerify { dataSource.requestRecipes(eq(0), eq(6)) }
}
@Test
fun `when append then request params correct`(): Unit = runBlocking {
mockServer.enqueueSuccessfulRecipeSummaryResponse()
fun `when append then request params correct`() = runTest {
coEvery { dataSource.requestRecipes(any(), any()) } returns TEST_RECIPE_SUMMARIES
subject.load(REFRESH, pagingState())
mockServer.takeRequest()
mockServer.enqueueSuccessfulRecipeSummaryResponse()
subject.load(APPEND, pagingState())
val actual = mockServer.takeRequest().path
assertThat(actual).isEqualTo("/api/recipes/summary?start=2&limit=2")
coVerify {
dataSource.requestRecipes(eq(0), eq(6))
dataSource.requestRecipes(eq(2), eq(2))
}
}
@Test
fun `when append fails then recipes aren't removed`(): Unit = runBlocking {
mockServer.enqueueSuccessfulRecipeSummaryResponse()
fun `when append fails then recipes aren't removed`() = runTest {
coEvery { dataSource.requestRecipes(any(), any()) } returns TEST_RECIPE_SUMMARIES
subject.load(REFRESH, pagingState())
mockServer.takeRequest()
mockServer.enqueueUnsuccessfulRecipeResponse()
coEvery { dataSource.requestRecipes(any(), any()) } throws Unauthorized(RuntimeException())
subject.load(APPEND, pagingState())
val actual = appDb.recipeDao().queryAllRecipes()
assertThat(actual).isEqualTo(TEST_RECIPE_ENTITIES)
coVerify {
storage.refreshAll(TEST_RECIPE_SUMMARIES)
}
}
private fun pagingState(

View File

@@ -1,35 +1,10 @@
package gq.kirmanak.mealient.test
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import java.nio.charset.Charset
object AuthImplTestData {
const val TEST_USERNAME = "TEST_USERNAME"
const val TEST_PASSWORD = "TEST_PASSWORD"
const val TEST_BASE_URL = "https://example.com/"
const val TEST_TOKEN = "TEST_TOKEN"
const val SUCCESSFUL_AUTH_RESPONSE =
"{\"access_token\":\"$TEST_TOKEN\",\"token_type\":\"TEST_TOKEN_TYPE\"}"
const val UNSUCCESSFUL_AUTH_RESPONSE =
"{\"detail\":\"Unauthorized\"}"
const val TEST_AUTH_HEADER = "Bearer TEST_TOKEN"
const val TEST_URL = "TEST_URL"
fun RecordedRequest.body() = body.readString(Charset.defaultCharset())
fun MockWebServer.enqueueUnsuccessfulAuthResponse() {
val response = MockResponse()
.setBody(UNSUCCESSFUL_AUTH_RESPONSE)
.setHeader("Content-Type", "application/json")
.setResponseCode(401)
enqueue(response)
}
fun MockWebServer.enqueueSuccessfulAuthResponse() {
val response = MockResponse()
.setBody(SUCCESSFUL_AUTH_RESPONSE)
.setHeader("Content-Type", "application/json")
.setResponseCode(200)
enqueue(response)
}
}

View File

@@ -1,23 +0,0 @@
package gq.kirmanak.mealient.test
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
abstract class MockServerTest : HiltRobolectricTest() {
lateinit var mockServer: MockWebServer
lateinit var serverUrl: String
@Before
fun startMockServer() {
mockServer = MockWebServer().apply {
start()
}
serverUrl = mockServer.url("/").toString()
}
@After
fun stopMockServer() {
mockServer.shutdown()
}
}

View File

@@ -1,21 +0,0 @@
package gq.kirmanak.mealient.test
import gq.kirmanak.mealient.data.auth.AuthRepo
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_PASSWORD
import gq.kirmanak.mealient.test.AuthImplTestData.TEST_USERNAME
import gq.kirmanak.mealient.test.AuthImplTestData.enqueueSuccessfulAuthResponse
import kotlinx.coroutines.runBlocking
import org.junit.Before
import javax.inject.Inject
abstract class MockServerWithAuthTest : MockServerTest() {
@Inject
lateinit var authRepo: AuthRepo
@Before
fun authenticate(): Unit = runBlocking {
mockServer.enqueueSuccessfulAuthResponse()
authRepo.authenticate(TEST_USERNAME, TEST_PASSWORD, serverUrl)
mockServer.takeRequest()
}
}

View File

@@ -11,8 +11,6 @@ import gq.kirmanak.mealient.data.recipes.network.response.GetRecipeResponse
import gq.kirmanak.mealient.data.recipes.network.response.GetRecipeSummaryResponse
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
object RecipeImplTestData {
val RECIPE_SUMMARY_CAKE = GetRecipeSummaryResponse(
@@ -43,37 +41,6 @@ object RecipeImplTestData {
val TEST_RECIPE_SUMMARIES = listOf(RECIPE_SUMMARY_CAKE, RECIPE_SUMMARY_PORRIDGE)
const val RECIPE_SUMMARY_SUCCESSFUL = """[
{
"id": 1,
"name": "Cake",
"slug": "cake",
"image": "86",
"description": "A tasty cake",
"recipeCategory": ["dessert", "tasty"],
"tags": ["gluten", "allergic"],
"rating": 4,
"dateAdded": "2021-11-13",
"dateUpdated": "2021-11-13T15:30:13"
},
{
"id": 2,
"name": "Porridge",
"slug": "porridge",
"image": "89",
"description": "A tasty porridge",
"recipeCategory": ["porridge", "tasty"],
"tags": ["gluten", "milk"],
"rating": 5,
"dateAdded": "2021-11-12",
"dateUpdated": "2021-10-13T17:35:23"
}
]"""
const val RECIPE_SUMMARY_UNSUCCESSFUL = """
{"detail":"Unauthorized"}
"""
val CAKE_RECIPE_SUMMARY_ENTITY = RecipeSummaryEntity(
remoteId = 1,
name = "Cake",
@@ -96,25 +63,7 @@ object RecipeImplTestData {
dateUpdated = LocalDateTime.parse("2021-10-13T17:35:23"),
)
val TEST_RECIPE_ENTITIES = listOf(CAKE_RECIPE_SUMMARY_ENTITY, PORRIDGE_RECIPE_SUMMARY_ENTITY)
fun MockWebServer.enqueueSuccessfulRecipeSummaryResponse() {
val response = MockResponse()
.setBody(RECIPE_SUMMARY_SUCCESSFUL)
.setHeader("Content-Type", "application/json")
.setResponseCode(200)
enqueue(response)
}
fun MockWebServer.enqueueUnsuccessfulRecipeResponse() {
val response = MockResponse()
.setBody(RECIPE_SUMMARY_UNSUCCESSFUL)
.setHeader("Content-Type", "application/json")
.setResponseCode(401)
enqueue(response)
}
val SUGAR_INGREDIENT = GetRecipeIngredientResponse(
private val SUGAR_INGREDIENT = GetRecipeIngredientResponse(
title = "Sugar",
note = "2 oz of white sugar",
unit = "",
@@ -132,7 +81,7 @@ object RecipeImplTestData {
quantity = 2
)
val MILK_INGREDIENT = GetRecipeIngredientResponse(
private val MILK_INGREDIENT = GetRecipeIngredientResponse(
title = "Milk",
note = "2 oz of white milk",
unit = "",
@@ -146,12 +95,12 @@ object RecipeImplTestData {
text = "Mix the ingredients"
)
val BAKE_INSTRUCTION = GetRecipeInstructionResponse(
private val BAKE_INSTRUCTION = GetRecipeInstructionResponse(
title = "Bake",
text = "Bake the ingredients"
)
val BOIL_INSTRUCTION = GetRecipeInstructionResponse(
private val BOIL_INSTRUCTION = GetRecipeInstructionResponse(
title = "Boil",
text = "Boil the ingredients"
)
@@ -172,110 +121,6 @@ object RecipeImplTestData {
recipeInstructions = listOf(MIX_INSTRUCTION, BAKE_INSTRUCTION)
)
val GET_CAKE_RESPONSE_BODY = """
{
"id": 1,
"name": "Cake",
"slug": "cake",
"image": "86",
"description": "A tasty cake",
"recipeCategory": ["dessert", "tasty"],
"tags": ["gluten", "allergic"],
"rating": 4,
"dateAdded": "2021-11-13",
"dateUpdated": "2021-11-13T15:30:13",
"recipeYield": "4 servings",
"recipeIngredient": [
{
"title": "Sugar",
"note": "2 oz of white sugar",
"unit": null,
"food": null,
"disableAmount": true,
"quantity": 1
},
{
"title": "Bread",
"note": "2 oz of white bread",
"unit": null,
"food": null,
"disableAmount": false,
"quantity": 2
}
],
"recipeInstructions": [
{
"title": "Mix",
"text": "Mix the ingredients"
},
{
"title": "Bake",
"text": "Bake the ingredients"
}
],
"nutrition": {
"calories": "100",
"fatContent": "20",
"proteinContent": "30",
"carbohydrateContent": "40",
"fiberContent": "50",
"sodiumContent": "23",
"sugarContent": "53"
},
"tools": [],
"totalTime": "12 hours",
"prepTime": "1 hour",
"performTime": "4 hours",
"settings": {
"public": true,
"showNutrition": true,
"showAssets": true,
"landscapeView": true,
"disableComments": false,
"disableAmount": false
},
"assets": [],
"notes": [
{
"title": "Note title",
"text": "Note text"
},
{
"title": "Second note",
"text": "Second note text"
}
],
"orgURL": null,
"extras": {},
"comments": [
{
"text": "A new comment",
"id": 1,
"uuid": "476ebc15-f794-4eda-8380-d77bba47f839",
"recipeSlug": "test-recipe",
"dateAdded": "2021-11-19T22:13:23.862459",
"user": {
"id": 1,
"username": "kirmanak",
"admin": true
}
},
{
"text": "A second comment",
"id": 2,
"uuid": "20498eba-9639-4acd-ba0a-4829ee06915a",
"recipeSlug": "test-recipe",
"dateAdded": "2021-11-19T22:13:29.912314",
"user": {
"id": 1,
"username": "kirmanak",
"admin": true
}
}
]
}
""".trimIndent()
val GET_PORRIDGE_RESPONSE = GetRecipeResponse(
remoteId = 2,
name = "Porridge",
@@ -299,19 +144,19 @@ object RecipeImplTestData {
text = "Mix the ingredients",
)
val BAKE_CAKE_RECIPE_INSTRUCTION_ENTITY = RecipeInstructionEntity(
private val BAKE_CAKE_RECIPE_INSTRUCTION_ENTITY = RecipeInstructionEntity(
localId = 2,
recipeId = 1,
title = "Bake",
text = "Bake the ingredients",
)
val CAKE_RECIPE_ENTITY = RecipeEntity(
private val CAKE_RECIPE_ENTITY = RecipeEntity(
remoteId = 1,
recipeYield = "4 servings"
)
val CAKE_SUGAR_RECIPE_INGREDIENT_ENTITY = RecipeIngredientEntity(
private val CAKE_SUGAR_RECIPE_INGREDIENT_ENTITY = RecipeIngredientEntity(
localId = 1,
recipeId = 1,
title = "Sugar",
@@ -346,12 +191,12 @@ object RecipeImplTestData {
),
)
val PORRIDGE_RECIPE_ENTITY_FULL = RecipeEntity(
private val PORRIDGE_RECIPE_ENTITY_FULL = RecipeEntity(
remoteId = 2,
recipeYield = "3 servings"
)
val PORRIDGE_MILK_RECIPE_INGREDIENT_ENTITY = RecipeIngredientEntity(
private val PORRIDGE_MILK_RECIPE_INGREDIENT_ENTITY = RecipeIngredientEntity(
localId = 4,
recipeId = 2,
title = "Milk",
@@ -362,7 +207,7 @@ object RecipeImplTestData {
quantity = 3
)
val PORRIDGE_SUGAR_RECIPE_INGREDIENT_ENTITY = RecipeIngredientEntity(
private val PORRIDGE_SUGAR_RECIPE_INGREDIENT_ENTITY = RecipeIngredientEntity(
localId = 3,
recipeId = 2,
title = "Sugar",
@@ -373,14 +218,14 @@ object RecipeImplTestData {
quantity = 1
)
val PORRIDGE_MIX_RECIPE_INSTRUCTION_ENTITY = RecipeInstructionEntity(
private val PORRIDGE_MIX_RECIPE_INSTRUCTION_ENTITY = RecipeInstructionEntity(
localId = 3,
recipeId = 2,
title = "Mix",
text = "Mix the ingredients"
)
val PORRIDGE_BOIL_RECIPE_INSTRUCTION_ENTITY = RecipeInstructionEntity(
private val PORRIDGE_BOIL_RECIPE_INSTRUCTION_ENTITY = RecipeInstructionEntity(
localId = 4,
recipeId = 2,
title = "Boil",
@@ -399,12 +244,4 @@ object RecipeImplTestData {
PORRIDGE_BOIL_RECIPE_INSTRUCTION_ENTITY,
)
)
fun MockWebServer.enqueueSuccessfulGetRecipe() {
val response = MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "application/json")
.setBody(GET_CAKE_RESPONSE_BODY)
enqueue(response)
}
}

View File

@@ -0,0 +1,10 @@
package gq.kirmanak.mealient.test
import android.app.Application
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
@RunWith(AndroidJUnit4::class)
@Config(application = Application::class, manifest = Config.NONE)
abstract class RobolectricTest

View File

@@ -0,0 +1,6 @@
package gq.kirmanak.mealient.test
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody
fun String.toJsonResponseBody() = toResponseBody("application/json".toMediaType())

View File

@@ -3,7 +3,8 @@ package gq.kirmanak.mealient.ui.disclaimer
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import gq.kirmanak.mealient.data.disclaimer.DisclaimerStorage
import gq.kirmanak.mealient.test.HiltRobolectricTest
import io.mockk.MockKAnnotations
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.test.currentTime
@@ -11,18 +12,18 @@ import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import java.util.concurrent.TimeUnit
import javax.inject.Inject
@ExperimentalCoroutinesApi
@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
class DisclaimerViewModelTest : HiltRobolectricTest() {
@Inject
class DisclaimerViewModelTest {
@MockK(relaxUnitFun = true)
lateinit var storage: DisclaimerStorage
lateinit var subject: DisclaimerViewModel
@Before
fun setUp() {
MockKAnnotations.init(this)
subject = DisclaimerViewModel(storage)
}