DEV Community

LiHan
LiHan

Posted on • Updated on

[Android] UserListApp - UnitTest -Part6

Add Test Dependency

okhttp3.4.9 is match mockwebserver4.9.3

    //Mock Server
    testImplementation 'com.squareup.okhttp3:mockwebserver:4.9.3'
    //okhttp
    implementation 'com.squareup.okhttp3:okhttp:3.4.9'
    //Truth
    testImplementation "com.google.truth:truth:1.1"
    testImplementation 'junit:junit:4.13.2'
Enter fullscreen mode Exit fullscreen mode

Create TestFile

CreateTestFile

CreateTestFile2

UserRepositoryTest

This test is test for api send , success and fail

class UserRepositoryImplTest {

    private lateinit var userRepository: UserRepository
    private lateinit var mockWebServer : MockWebServer

    @Before
    fun setUp() {
        mockWebServer = MockWebServer()
        val retrofit = Retrofit.Builder()
            .baseUrl(mockWebServer.url(""))
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        val userApi = retrofit.create(UserApi::class.java)
        userRepository = UserRepositoryImpl(userApi)
    }

    @After
    fun tearDown() {
        mockWebServer.shutdown()
    }

    @Test
    fun `getRandomUserWhenSuccess`() = runBlocking{
        mockWebServer.enqueue(
            MockResponse()
                .setResponseCode(200)
                .setBody(UserDumpData.result)
        )

        var user : User?=null
        var errorMessage = ""
        userRepository.getRandomUser().collectLatest {
            user = it.data
            errorMessage = it.message?:""
        }
        assertTrue(user !=  null)
        assertTrue(errorMessage.isEmpty())
    }
    @Test
    fun `getRandomUserWhenFailed`() = runBlocking{
        mockWebServer.enqueue(
            MockResponse()
                .setResponseCode(404)
                .setBody("{}")
        )

        var user : User?=null
        var errorMessage = ""
        userRepository.getRandomUser().collectLatest {
            user = it.data
            errorMessage = it.message?:""
        }
        assertTrue(user ==  null)
        assertTrue(errorMessage.isNotEmpty())
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)