Issue with lateinit in test case - unit-testing

I have a kotlin Ut like below
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class FileOpenerTest {
private val file = mockk<Resource>()
private lateinit var target: FileOpener
#BeforeAll
fun setup() {
val file = File("./src/test/resources/sample.csv")
every { file.file } returns file
target = FileOpener(file)
}
#Test
fun `get documents for indexing from file`() {
val docs = target.startIndexing()
verify { docs.size == 3 }
}
}
the test case is always failing saying
kotlin.UninitializedPropertyAccessException: lateinit property target has not been initialized
But I am initialising it in the setup method, please help me to fix the issue ?

Your setup annotation #BeforeAll is applied only on static functions:
#BeforeAll annotated method MUST be a static method otherwise it will throw runtime error.
Source
So your method is not executed in JUnit. Either put the method and the field in your companion object or initialize it differently, like with #Before

Related

Mockito.when().thenReturn() not working as expected

New to Mockito.
I am testing a function inside class A, inside the class A constructor, I have class B. (I need to use a method from class B). Here's the code:
class A #Inject constructor(
private val bAccessor: B
)
fun buildInfo(number, name): Map<String,String> {
val graph = bAccessor.getGraph(
number,
name
)
val filters = GraphParser.getRefinement(graph)
return filters.entries.associate {
val bin = it.key to Bin
.builder()
.withRestrict(it.value)
.build()
bin
}
}
My unit test is testing the class A - buildInfo function,
Below is my unit test code:
#Mock
private lateinit var graph: Graph
#Mock
private lateinit var b: B
#InjectMocks
private lateinit var a: A
#BeforeEach
fun setup() {
MockitoAnnotations.initMocks(this)
}
#Test
fun `test buildInfo`() {
`when`(b.getGraph("123456", "Test")).thenReturn(graph)
var info = a.buildInfo("123456", "Test")
assertTrue(info.isNotEmpty())
assertTrue(info.containsKey("refinement_key"))
assertEquals("refinement_value", info["refinement_key"])
The test fail because:
java.lang.IllegalArgumentException: Parameter specified as non-null is null:
method GraphParser.getRefinement, parameter graph
at GraphParser.getRefinement(GraphView.kt)
at A.buildInfo(A.kt:178)
getRefinement method can only accept the Graph object. I don't want to actually call the b, so I've mocked the answer above like this:
`when`(b.getGraph("123456", "Test")).thenReturn(graph)
But why it indicates the graph is null even if I return a graph?
A parenthesis is missed before thenReturn:
_actual: `when`(b.getGraph("123456", "Test").thenReturn(graph)
correct: `when`(b.getGraph("123456", "Test")).thenReturn(graph)
^
missed symbol

Not able to mock private methods using POWERMOCK and mockito

even when I am using the spy method, I am not able to mock the getContext() method of attributesStorage() to get my context.
this is my code :
class Rich
{
fun method1() : HashMap<String,String>
{
val x = attributeStorage().getStore()
return x
}
}
class AttributeStorage
{
private fun getContext()
{
return MyProject.instance.context()
}
fun getStore()
{
//some work done,
return HashMap<String,String>()
}
}
#PrepareForTest(Rich::class)
class RichTest {
#Mock
lateinit var mcontext: Context
fun init()
{
mcontext = Mockito.mock(Context::class.java)
val mAttributesStorage = spy(AttributesStorage())
`when`<Context>(mAttributesStorage,"getContext").thenReturn(mcontext)
Mockito.`when`(mAttributesStorage.getStore()).thenReturn(mapOf("1" to "1"))
}
fun test()
{
//gives an error because the getContext() couldn't be mocked
}
}
I looked at every question possible on stack overflow and went through powermock and mockito documentation but couldn't find a solution to this.
#Mock
lateinit var mcontext: Context
and
mcontext = Mockito.mock(Context::class.java)
are one too many. Use either the one or the other (annotation preferred, of course).
See Shorthand for mocks creation - #Mock annotation:
Important! This needs to be somewhere in the base class or a test runner:
MockitoAnnotations.initMocks(testClass);
Regarding your last code comment: objects are mocked, methods are stubbed.

How to Implement Unit test on my retrofit2 presenter using mockito?

i want to make a unit testing by using mockito dependencies on my code. it is always failed because view.processMatchData(data) and view.hideLoading() are in closure part in this presenter code, so that unit test will not detect them. Please, somebody help me solve this problem.
open class MatchSearchPresenter(
private val view: MatchSearchView,
private val apiService: ApiService,
private val cari : String
) {
fun searchMatch() {
view.showLoading()
apiService.loadSearchMatch(cari).enqueue(object : Callback<MatchSearchResponseModel> {
override fun onResponse(call: Call<MatchSearchResponseModel>, response: Response<MatchSearchResponseModel>)
{
if (response.isSuccessful) {
val data = response.body()!!
view.processMatchData(data)
}
view.hideLoading()
}
override fun onFailure(call: Call<MatchSearchResponseModel>, error: Throwable)
{
Log.e("Error", error.message)
view.hideLoading()
}
})
}
}
here are my unit test :
class MatchSearchPresenterTest {
#Mock
private lateinit var view: MatchSearchView
#Mock
private lateinit var apiService: ApiService
#Mock
private lateinit var teamPresenter: MatchSearchPresenter
#Mock
private lateinit var call: Call<MatchSearchResponseModel>
#Mock
private lateinit var something: Callback<MatchSearchResponseModel>
#Before
fun setUp() {
MockitoAnnotations.initMocks(this)
val kata = "Man United"
teamPresenter = MatchSearchPresenter(view, apiService, kata )
}
#Test
fun searchMatch() {
val teamId = "Man United"
val teams: MutableList<PrevMatchData> = mutableListOf()
val data = MatchSearchResponseModel(teams)
teamPresenter.searchMatch()
argumentCaptor<MatchSearchView>().apply {
Mockito.verify(apiService.loadSearchMatch(teamId).enqueue(something))
firstValue.processMatchData(data)
firstValue.hideLoading()
}
Mockito.verify(view).showLoading()
Mockito.verify(view).processMatchData(data)
Mockito.verify(view).hideLoading()
}
}
but this is not working by showing message like this :
java.lang.NullPointerException
at com.example.footballleaguecataloguefourth.ui_bottom_navigation.schedule.match_search.MatchSearchPresenter.searchMatch(MatchSearchPresenter.kt:19)
at com.example.footballleaguecataloguefourth.ui_bottom_navigation.schedule.match_search.MatchSearchPresenterTest.searchMatch(MatchSearchPresenterTest.kt:41)
I think what you want here is to have the call returned by ApiService call the correct method as soon as it's enqueued.
To do this you can use Mockito's thenAnswer - Here's an example. In your case, you can try this:
Mockito.`when`(call.enqueue(Mockito.any())).thenAnswer {
(it.getArgument(0) as Callback<MatchSearchResponseModel>).onResponse(
call,
Response.success(MatchSearchResponseModel(/*whatever is needed to build this object*/))
)
}
Here, you make sure that once call.enqueue is called with any argument, it'll immediately call the onResponse method with a success reponse. You can do something similar for an error and you can also call onFailure.
The last thing you need to do is to make sure that your api service returns the configured mocked call:
Mockito.`when`(apiService.loadSearchMatch(kata)).thenReturn(call)
I'd put this per test. So before you call your presenter method, I'd configure the mocks like this.
Now, calling teamPresenter.searchMatch(), should call apiService.loadSearchMatch(cari), which will return the mocked call that once enqueued will call the passed callback's onResponse method.
Lastly, as you might have noticed when is actually written with backticks. This is because it's a kotlin keyword that needs to be escaped. Not only for this reason but many more, you could consider using Mockito Kotlin which is a superb kotlin library wrapping mockito and makes life much easier.

Why "getSharedPreferences" return null in unit testing?

My classes is written in Kotlin and here is my SharedPreferenceHandler
class SharedPreferenceHandler(sharedPrefs: SharedPreferences) {
companion object {
var mInstance: SharedPreferenceHandler = SharedPreferenceHandler(getPrefs())
private fun getPrefs(): SharedPreferences {
return Application.mInstance.getSharedPreferences(
"myApp", Context.MODE_PRIVATE)
}
fun getInstance(): SharedPreferenceHandler {
return mInstance
}
}
private var sharedPreferences = sharedPrefs
var accessToken: String?
get() = sharedPreferences.getString(SharedPreference.ACCESS_TOKEN.name, null)
set(token) = sharedPreferences.edit().putString(SharedPreference.ACCESS_TOKEN.name, token).apply()
}
Here is method called in presenter:
override fun reload(vm: ViewModel) {
super.updateViewModel(vm) {
//some stuffs
}
}
Here is my test method:
#Test
public void reload() {
when(SharedPreferenceHandler.Companion.getMInstance().getAccessToken()).thenReturn("234234234234234");
presenter.reload(viewModel);
}
In handler from super.updateViewModel(vm) I call "SharedPreferenceHandler.mInstance.accessToken!!)"
That is what is thrown:
Caused by: java.lang.IllegalStateException:
Application.mInstanc…m", Context.MODE_PRIVATE) must not be null
at
com.zuum.zuumapp.preferences.SharedPreferenceHandler$Companion.getPrefs(SharedPreferenceHandler.kt:18)
at
com.zuum.zuumapp.preferences.SharedPreferenceHandler$Companion.access$getPrefs(SharedPreferenceHandler.kt:14)
at
com.zuum.zuumapp.preferences.SharedPreferenceHandler.(SharedPreferenceHandler.kt:15)
I wanna to get accessToken by calling " SharedPreferenceHandler.mInstance.accessToken!!" in my test class.
Is possible to get that in my test method?
You can't use Android SharedPreferences in unit test, but you can mock your method call by this:
Mockito.`when`(SharedPreferenceHandler.mInstance.accessToken).thenReturn("token")
And return what you need.
You should not test your code this way. You should create an interface for class you want to mock:
interface MySharedPreferences {
fun getAccessToken(): String
}
Let your SharedPreferencesHandler implements this interface. Then in your presenter (or other class you want to test) inject dependencies (f.e. by constructor or framework like Dagger/Kodein) into your object. Then there is possibility to easy mock this interface. I assume in #Before you create class you test - and then just pass as param your mocked SharedPreferencesHandler.
Testing things with static dependencies is possible, but is but tricky (and a lot of people consider static dependencies as anti-pattern). How to do it is described here: How to android unit test and mock a static method
Example:
class MyPresenter(val sp: MySharedPreferences) {
/* some code here */
fun validateToken() {
if (sp.getAccessToken() == "") throw new Exception()
}
}
Like you see sp is injected into this class as parameter. Normally you don't create views/presenters etc. directly in code but by DI framework (like Dagger or Kodein). Anyway, static dependencies are not easy testable. Injected interface-dependencies can be mocked, and you operating not on object, but on behaviors (so it's bigger level of abstraction). So, now in your test all you have to do is:
class MyTest() {
#Mock lateinit var sharedPreferencesMock: MySharedPreferences
lateinit var instance: MyPresenter
#Before
fun setUp() {
instance = MyPresenter(sharedPreferencesMock)
}
#Test
fun testSomething() {
`when`(sharedPreferencesMock.getAccessToken()).thenReturn("myAccessToken")
/* here is your test body */
}
}

mockito InjectMocks not working?

I am trying to use a test implementation of a class and using that to be injected to the test using #InjectMocks but it doesn't seem to inject it. I tried using Spy but that did not work and instead created a blank mocked version instead of using the version I created inside my #Before function
Here is my test code below:
#Before
fun setup() {
someFunction = object : SomeFuntionContract {
override fun save(test: String) {
testData = test //breakpoint here but never executes
}
override fun get(): String {
return testData
}
}
}
lateinit var testData : String
#InjectMocks
lateinit var delegator: Delegator
#Spy
lateinit var someFunction: SomeFunctionContract
#Test
fun testSomething{
delegator.retrieve(something)
Assert.assertTrue(someFunction.get() == "hello")
}
SomeFunctionContract.kt is an interface that has save and get functions and SomeFunction is the real implementation test
Inside delegator.retrieve it calls someFunction.get inside it and I am trying to see if it gets called and saves the data.
Make sure you init the creation and injection of the mocks by:
1) Adding #RunWith(org.mockito.junit.MockitoJUnitRunner) on the test class.
or
2) Adding MockitoAnnotations.initMocks(this) to your #Before method.
The #Before method is called after Mockito does its injection magic so, you are overwriting the spy created and used by Mockito. If you want to have your own implementation of the object to be injected (I'm assuming it is SomeFunctionContract) then you have to declare it on the property instead of on the #Before function.
All that said, I think we are missing some context of your code. Can you attach the code for something, Delegator and testData?
Fixed:
initialise the implementation directly in the spy level:
#Spy
lateinit var someFunction: SomeFunctionContract = = object : SomeFuntionContract {
override fun save(test: String) {
testData = test //breakpoint here but never executes
}
override fun get(): String {
return testData
}
}