Skip to content

Instantly share code, notes, and snippets.

@ProArun
Created August 19, 2023 17:21
Show Gist options
  • Save ProArun/2544ae57a770ff172adc4d3df9731011 to your computer and use it in GitHub Desktop.
Save ProArun/2544ae57a770ff172adc4d3df9731011 to your computer and use it in GitHub Desktop.
Mocking using mockito
{
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
implementation 'com.google.code.gson:gson:2.8.6'
testImplementation 'org.mockito:mockito-core:4.0.0'
testImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0'
}
data class User(
val id:Int,
val name:String,
val email:String,
val password:String
)
enum class LOGIN_STATUS{
INVALID_USER,
INVALID_PASSWORD,
UNKNOWN_ERROR,
SUCCESS
}
class UserRepository{
val users = listof<user>(
User(id:1,"John","[email protected]","John@123"),
User(id:2,"Wein","[email protected]","Wein@123"),
User(id:3,"Emily","[email protected]","Emily@123")
)
fun loginUser(email: String, password: String): LOGIN_STATUS{
//Fetch User From DB
val users = users.filter {user -> user.email == email}
return if (users.size == 1){
if(users[0].password == password){
LOGIN_STATUS.SUCCESS
}else{
LOGIN_STATUS.INVALID_PASSWORD
}
}else{
LOGIN_STATUS.INVALID_USER
}
}
}
class UserService(private val userRepository: UserRepository){
fun loginUser(email: String, password: String): String{
val status = userRepository.loginUser(email,password)
return when(status){
INVALID_USER -> "User does not exist"
INVALID_PASSWORD -> "Password is invalid"
UNKNOWN_ERROR -> "Unknown error occurred"
SUCCESS -> "logged in successfully"
}
}
}
class UserServiceTest {
@Mock
lateinit var userRepository: UserRepository
@Before
fun serup(){
MockitoAnnotations.openMocks(testClass:this)
Mockito.`when`(userRepository.loginUser(anyString(),anyString())).thenReturn(LOGIN_STATUS.SUCCESS)
}
@Test
fun testUserService(){
val sut = UserService(userRepository)
val status = sut.loginUser(email:"[email protected]",password:"111111")
Assert.assertEquals(expected:"Logged in successfully",status)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment