How to mock kotlin object for unit testing - unit-testing

I have a sample method(which I need to write test case) as given below,
fun setName(val auxName:String) {
val configUrl = getConfig(auxName)
}
I want to mock the getConfig method and return a specific string value.
getConfig is a method in a Kotlin Object as below,
object Configuration{
fun getConfig(auxName:String){
....
}
}
Below is the test that I tried
#Test
fun setTest()
{
val testname="test"
val testObject=Mockito.mock(Configuration::class.java)
doReturn("configTest").`when`(testObject).getConfig(Mockito.anyString())
setName(testname)
}
I am not getting any error but the method getConfig is not mocked. The actual implementation is executed. I tried using Powermockito also. Please help me with this

the problem is probably with singleton object, you can try this answer: https://stackoverflow.com/a/37978020/3703819

Related

Mockk: cannot specify an answer for method call

I have the following method call in my Kotlin class:
myService.trigger(id, processVariables, transientVariables)
... where "id" is a String, "processVariables" is a Java Map<String, Object> and "transientVariables" is a Kotlin MutableMap<String, Any>.
How to I specify the answer to return in a unit test for this circumstance? I have tried the following:
every { myService?.trigger(MY_ID, any(), any()) } returns unit
... but I get an error when the unit test runs:
io.mockk.MockKException: no answer found for: MyService(#2).trigger(MY_ID, {}, {key=value})
Thanks in advance for any assistance.
A workaround that can be compiled and results in a successful test run is to populate the Map with values:
val map = mapOf("Key" to "Value")
every { processInstance.processVariables } returns map
every { myService?.trigger(EXECUTION_ID, map, any()) } returns unit

Is it possible to test this Kotlin class?

I am trying to write unit test cases for a Kotlin class A and trying to mock return client() call present in test() method to unit test test() method:
A.kt kotlin class:
class A (par 1, par 2) : B(par 1, par 2) {
override fun test(item: String): Boolean {
return client()
}
}
B.kt kotlin class:
abstract class B(par 1, par 2) {
private val client: WebClient by lazy {
//does something
}
protected fun client(): WebClient = client
}
Is it possible to mock the client() call in test() method?
And if possible how to do it and what library should I use for mocking?
This should be doable using Mockito testing framework. However, mocking an object returned from a object's method would require mocking the object itself.
val mockOfA = Mockito.mock(A::class)
val mockOfClient = Mockito.mock(WebClient:class)
Mockito.when(mockOfA.test(anyString())).thenReturn(mockOfClient) // Mind your original snippet return type Boolean from A.test()
If your class A implements internal logic you want to test in your test scenario, there are two possible paths:
Create a Spy instead of a Mock. Mocks do only whatever you explicitly set them up to do. Spy 'falls back' to original implementation when it is not given any mock behaviour.
Rewrite you class A so that it depends on external dependency of a ClientProvider to get an instance of WebClient to return in method test() and inject a mock of said provider to your object of type A during the test.

RxJava, How can I write test code for disposable.clear()?

I am developing an Android app.
My app is based on the MVP pattern.
So when the Activity's lifecycle is terminated, the presenter's unsubscribe() function is called.
The unsubscribe() function just clear 'disposable'.
It's very simple code like below:
override fun unsubscribe() {
disposable.clear()
}
The unsubscribe() function is very simple, so I have not tested it before.
But today, I just want to increase the code coverage.
So I tried to write test code for this function.
My first try is:
#Test
fun unsubscribeTest() {
mPresenter.unsubscribe()
verify(mockDisposable).clear()
}
But I didn't know the clear() function is the function of CompositeDisposable class, not Disposable interface.
So I cannot use it as a mock.
I solved this using disposable.size().
I changed the disposable to settable/injectable.
So the result is:
#Test
fun unsubscribeTest() {
val d = CompositeDisposable()
mPresenter.disposable = d
assertEquals(0, mPresenter.disposable.size())
d.add(Observable.just("").subscribe())
assertEquals(1, mPresenter.disposable.size())
mPresenter.unsubscribe()
assertEquals(0, mPresenter.disposable.size())
}

Using Kotlin and Mockito to mock functions taking vararg parameters

I'm having trouble utilizing Powermock, Mockito, and Kotlin to mock up a return value when
the function signature that needs overriden contains varargs.
Function to mock/override:
public BoundStatement bind(Object... values);
Test File:
class DbSessionTest {
var preparedStatement: PreparedStatement? = null
#Mock
var boundStatement: BoundStatement? = null
#Before
fun setup() {
initMocks(this)
whenever(preparedStatement?.bind(any())).thenReturn(boundStatement)
// Also, have tried it like this
whenever(preparedStatement?.bind(any<Array<Any>>())).thenReturn(boundStatement)
}
}
The fuction in the actual code is called like so:
internal fun createBoundStatement(query: String, vararg params: Any): BoundStatement {
val preparedStatement = prepare(query)
val boundStatement = preparedStatement.bind(*params)
return boundStatement
}
When I step through and the varargs are dereferenced, it turns into an Object[].
When the object array contains all the same type, everything works fine, but when
it contains type String and type Integer, the mock fails to happen and null is
returned.
Note: I have also included com.nhaarman.mockito_kotlin.any package for their specific
any function and anyVararg, but that did not work either.
What is the proper way to mock this so that no matter the type in the Object array,
it will always return the mocked value?
Nicholas Hauschild's answer make me think about removing powermock and just going with regular mockito and junit separately and that worked. Removing powermock and Upgrading mockito to v2.18.3 fixed the issue.

specs2: Is there a way to use doNothing while mocking with Mockito?

Let's say that I have a mocked trait Foo:
trait Foo {
def op(x: String): Unit
}
and I mocked this interface using
val mockedFoo = mock[Foo]
I want the method op to throw an exception second time I call it, e.g.
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
trait Foo {
def op(x: String): Unit
}
class DummySpec extends Specification with Mockito {
"dummy" should {
"test" in {
val mockedFoo = mock[Foo]
org.mockito.Mockito.doNothing().doThrow(new RuntimeException).when(mockedFoo).op(any[String])
mockedFoo.op("This one should work fine") should not(throwAn[Exception])
mockedFoo.op("This one should throw an exception") should throwAn[Exception]
}
}
}
Is there a way to do this in specs2 style? e.g.
mockedFoo.op(any[String]) returns Unit thenThrows new RuntimeException
but this doesn't compile.
Thanks!
The Unit return type makes things a bit trickier as you can't just chain:
returns "foo" thenThrows new RuntimeException
But you can still solve this problem if you use answers like below:
mockedFoo.op(anyString) answers {args => } thenThrows new RuntimeException
See if this works for you.