Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: UploadViewModel 테스트 추가 #343

Merged
merged 15 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ android {
versionName "1.0.1"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
testInstrumentationRunner "com.now.naaga.HiltTestRunner"
buildConfigField "String", "BASE_URL", properties["BASE_URL"]
buildConfigField "String", "KAKAO_NATIVE_APP_KEY", properties["KAKAO_NATIVE_APP_KEY"]
resValue "string", "kakao_redirection_scheme", properties["kakao_redirection_scheme"]
Expand All @@ -45,6 +46,11 @@ android {
dataBinding {
enable = true
}
testOptions {
unitTests {
includeAndroidResources = true
}
}
}

dependencies {
Expand All @@ -54,6 +60,7 @@ dependencies {
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation project(path: ':domain')
implementation 'androidx.test:runner:1.5.2'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
Expand Down Expand Up @@ -112,11 +119,19 @@ dependencies {
// ViewModel Test
testImplementation("androidx.arch.core:core-testing:2.2.0")

// Robolectric
testImplementation("org.robolectric:robolectric:4.9")

// hilt
implementation "com.google.dagger:hilt-android:2.44"
kapt "com.google.dagger:hilt-compiler:2.44"

implementation "androidx.activity:activity-ktx:1.7.2"

// For Robolectric tests.
testImplementation 'com.google.dagger:hilt-android-testing:2.44'
// ...with Kotlin.
kaptTest 'com.google.dagger:hilt-android-compiler:2.44'
}

// Allow references to generated code
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ class UploadActivity : AppCompatActivity(), AnalyticsDelegate by DefaultAnalytic
private fun initViewModel() {
binding.lifecycleOwner = this
binding.viewModel = viewModel
setClickListeners()
}

private fun subscribe() {
Expand Down Expand Up @@ -257,23 +256,7 @@ class UploadActivity : AppCompatActivity(), AnalyticsDelegate by DefaultAnalytic
}

private fun isFormValid(): Boolean {
return (isEmptyPhoto() || isEmptyTitle() || isEmptyCoordinate() || isEmptyDescription()).not()
}

private fun isEmptyPhoto(): Boolean {
return viewModel.hasUri().not()
}

private fun isEmptyTitle(): Boolean {
return viewModel.title.value == null
}

private fun isEmptyCoordinate(): Boolean {
return viewModel.hasCoordinate().not()
}

private fun isEmptyDescription(): Boolean {
return viewModel.description.value == null
return viewModel.isFormValid()
}

private fun Coordinate.toText(): String {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.now.naaga.presentation.upload

import android.net.Uri
import android.text.Editable
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
Expand All @@ -23,11 +21,9 @@ class UploadViewModel @Inject constructor(
) : ViewModel() {
private var imageUri: String = URI_EMPTY

private val _name = MutableLiveData<String>()
val title: LiveData<String> = _name
val name = MutableLiveData<String>()

private val _description = MutableLiveData<String>()
val description: LiveData<String> = _description
val description = MutableLiveData<String>()

private val _successUpload = MutableSingleLiveData<UploadStatus>()
val successUpload: SingleLiveData<UploadStatus> = _successUpload
Expand All @@ -38,14 +34,6 @@ class UploadViewModel @Inject constructor(
private val _coordinate = MutableLiveData<Coordinate>()
val coordinate: LiveData<Coordinate> = _coordinate

fun setTitle(editTitle: Editable) {
_name.value = editTitle.toString()
}

fun setDescription(editTitle: Editable) {
_description.value = editTitle.toString()
}

fun setUri(uri: String) {
imageUri = uri
}
Expand All @@ -54,12 +42,9 @@ class UploadViewModel @Inject constructor(
_coordinate.value = coordinate
}

fun hasUri(): Boolean {
return imageUri != URI_EMPTY
}

fun hasCoordinate(): Boolean {
return _coordinate.value != null
fun isFormValid(): Boolean {
return (imageUri != URI_EMPTY) && (_coordinate.value != null) &&
(name.value != null) && (description.value != null)
}

fun postPlace() {
Expand All @@ -68,8 +53,8 @@ class UploadViewModel @Inject constructor(
viewModelScope.launch {
runCatching {
placeRepository.postPlace(
name = _name.value.toString(),
description = _description.value.toString(),
name = name.value.toString(),
description = description.value.toString(),
coordinate = coordinate,
image = imageUri,
)
Expand All @@ -92,7 +77,7 @@ class UploadViewModel @Inject constructor(
}

companion object {
val URI_EMPTY = Uri.EMPTY.toString()
const val URI_EMPTY = "EMPTY"

const val ALREADY_EXISTS_NEARBY = 505
const val ERROR_STORE_PHOTO = 215
Expand Down
18 changes: 8 additions & 10 deletions android/app/src/main/res/layout/activity_upload.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@
android:id="@+id/lottie_upload_loading"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="80dp"
android:elevation="4dp"
android:background="@color/main_gray_opacity_medium"
app:layout_constraintTop_toTopOf="parent"
android:elevation="4dp"
android:padding="80dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:lottie_rawRes="@raw/simple_loading"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_autoPlay="true"
app:lottie_loop="true"
app:lottie_autoPlay="true" />
app:lottie_rawRes="@raw/simple_loading" />

<ImageView
android:id="@+id/iv_upload_photo"
Expand Down Expand Up @@ -61,13 +61,12 @@
android:layout_height="wrap_content"
android:layout_marginHorizontal="@dimen/space_default_large"
android:layout_marginTop="@dimen/space_default_medium"
android:afterTextChanged="@{viewModel::setTitle}"
android:autofillHints="no"
android:ellipsize="end"
android:hint="@string/upload_photo_title"
android:inputType="text"
android:maxLines="1"
android:text="@{viewModel.title}"
android:text="@={viewModel.name}"
android:textAlignment="textStart"
android:textSize="28sp"
app:layout_constraintEnd_toEndOf="parent"
Expand Down Expand Up @@ -127,7 +126,6 @@
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="@dimen/space_default_medium"
android:afterTextChanged="@{viewModel::setDescription}"
android:autofillHints="no"
android:background="@drawable/rect_radius_small"
android:backgroundTint="@color/white"
Expand All @@ -136,7 +134,7 @@
android:hint="@string/upload_photo_description"
android:inputType="text"
android:padding="@dimen/space_default_medium"
android:text="@{viewModel.description}"
android:text="@={viewModel.description}"
app:layout_constraintBottom_toTopOf="@id/v_upload_divide_line_2"
app:layout_constraintEnd_toEndOf="@id/et_upload_photo_title"
app:layout_constraintStart_toStartOf="@id/et_upload_photo_title"
Expand Down
16 changes: 16 additions & 0 deletions android/app/src/test/java/com/now/naaga/HiltTestRunner.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.now.naaga

import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import dagger.hilt.android.testing.HiltTestApplication

class HiltTestRunner : AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?,
): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
}
110 changes: 110 additions & 0 deletions android/app/src/test/java/com/now/naaga/UploadViewModelTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package com.now.naaga

import android.text.Editable
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.now.domain.model.Coordinate
import com.now.domain.model.Place
import com.now.domain.repository.PlaceRepository
import com.now.naaga.data.throwable.DataThrowable
import com.now.naaga.presentation.upload.UploadStatus
import com.now.naaga.presentation.upload.UploadViewModel
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test

class UploadViewModelTest {
private lateinit var viewModel: UploadViewModel
private lateinit var placeRepository: PlaceRepository

// 라이브데이터가 메인 스레드에서 동작하도록 함
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()

@OptIn(ExperimentalCoroutinesApi::class)
@Before
fun setup() {
Dispatchers.setMain(UnconfinedTestDispatcher())
placeRepository = mockk()
viewModel = UploadViewModel(placeRepository)
}

@OptIn(ExperimentalCoroutinesApi::class)
@After
fun tearDown() {
Dispatchers.resetMain()
}

private fun String.toEditable(): Editable {
return Editable.Factory.getInstance().newEditable(this)
}

@Test
fun `Coordinate이 입력되면 뷰모델의 Coordinate도 바뀐다`() {
// given
val coordinate = Coordinate(123.4567, 37.890)

// when
viewModel.setCoordinate(coordinate)

// then
assertEquals(Coordinate(123.4567, 37.890), viewModel.coordinate.value)
}

@Test
fun `데이터 전송 성공시 successUpload가 UploadStatus SUCCESS다`() {
// given
val coordinate = Coordinate(123.4567, 37.890)
viewModel.setCoordinate(coordinate)

coEvery {
placeRepository.postPlace(any(), any(), any(), any())
} returns (
Place(
id = 1,
name = "krrong",
coordinate = Coordinate(37.1234, 127.1234),
image = "https://img.segye.com/content/image/2021/07/29/20210729513138.jpg",
description = "android",
)
)

// when
viewModel.postPlace()

// Assert: 결과 확인
assertEquals(UploadStatus.SUCCESS, viewModel.successUpload.getValue())
}

@Test
fun `데이터 전송 실패시 successUpload가 UploadStatus Fail이고 반환된 throwable이 저장된다`() {
// given
val coordinate = Coordinate(123.4567, 37.890)
viewModel.setCoordinate(coordinate)
val placeThrowable = DataThrowable.PlaceThrowable(505, "Test Failure")
coEvery { placeRepository.postPlace(any(), any(), any(), any()) } throws placeThrowable

// when
runBlocking { viewModel.postPlace() }

// then
// placeRepository.postPlace가 실행되었는지 확인
coVerify { placeRepository.postPlace(any(), any(), any(), any()) }

// successUpload가 UploadStatus.Fail 인지 확인
assertEquals(UploadStatus.FAIL, viewModel.successUpload.getValue())

// 의도한 throwable이 저장되었는지 확인
assertEquals(placeThrowable, viewModel.throwable.value)
}
}
Loading
Loading