https://kotlinlang.org logo
#compose
Title
# compose
a

Alexa_Gal

09/22/2021, 7:10 PM
Hi guys 👩‍💻 looking for some testing advices i want to create my first
androidTest
and im having some problems trying to mock the ViewController of my view, maybe im doing something working but i would like to test only the view without the view controller (i already have the Unit test for my view controller) how would you do it using hilt and compose-navigation (
HiltAndroidTest
)
p

Peter Mandeljc

09/23/2021, 1:46 PM
I usually make another composable, that doesn't require controller as a parameter. For example
Copy code
fun LoginScreen(vm: LoginViewModel = hiltViewModel(), onPopBack: () -> Unit) {
    val state by vm.anyState.collectAsState()
    LoginView(state, onPopBack)
}

// Test this
fun LoginView(anyStateFromVM: ?, onPopBack: () -> Unit) {
    // ...
}
a

Alexa_Gal

09/23/2021, 4:33 PM
would you also pass the functions and state needed on the view e.g
doLogin: vm.doLogin...
?
p

Peter Mandeljc

09/23/2021, 5:03 PM
Yeah, pass all the state, that is provided by VM and expose all callbacks that call VM functions
Copy code
LoginView(state, onPopBack, onLogin: vm::onLogin)
a

Alexa_Gal

09/23/2021, 5:04 PM
nice, ill try to implement something similar thanks peter 🙂
p

Peter Mandeljc

09/23/2021, 5:05 PM
But you still miss a bit of test coverage, if you test it without VM. In my example LoginScreen isn't tested
a

Alexa_Gal

09/23/2021, 5:05 PM
i have a unit test for the VM that one covers the logic there
🤔
p

Peter Mandeljc

09/23/2021, 5:07 PM
tough you can always make an instance of LoginViewModel, by simply call constructor
LoginViewModel()
, you don't need to call
hiltViewModel<LoginViewModel>()
a

Alexa_Gal

09/23/2021, 5:10 PM
that could be a bit more complex since i have @inject props coming from hilt i would need to create one VM with mock props 🤔 dont you think?
p

Peter Mandeljc

09/23/2021, 5:11 PM
yeah, exactly
❤️ 1
3 Views