I am using Mockk in my project. I am trying to mock my extension function but it cannot find my function. I tried some piece of code but it cannot find the extension function inside my test. Can someone guide me, How can I solve this issue. Thanks
ExploreConsultationsActivity.kt
class ExploreConsultationsActivity : AppCompactActvity () {
... // more function
internal fun setupExploreConsultationVisibility(hasFocus: Boolean) {
if (hasFocus) {
.....
} else if (viewModel.queryText.isEmpty()) {
binding.consultationViewSwitcher.displayConsultationViewSwitcherChild(0)
}
}
internal fun ViewSwitcher.displayConsultationViewSwitcherChild(childNumber: Int) {
visible()
displayedChild = childNumber
}
}
ExploreConsultationsActivityTest.kt
class ExploreConsultationsActivityTest {
#get:Rule
val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()
private val subject by lazy { spyk(ExploreConsultationsActivity()) }
#MockK private lateinit var mockConsultationViewSwitcher: ViewSwitcher
#Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
setupMockView()
}
private fun setupMockView() {
mockkStatic(ExploreConsultationsLayoutBinding::class)
every { mockRootView.findViewById<ChipGroup>(R.id.exploreConsultationChips) } returns mockChipGroup
}
#Test
fun `setupExploreConsultationVisibility - `() {
// STUBBING
mockViewModel.queryText = ""
every { mockViewModel.topicSelected } returns ConsultationTopicsArea.ALL
with(mockConsultationViewSwitcher){
any<ViewSwitcher>().displayConsultationViewSwitcherChild(0)
}
// EXECUTION
subject.setupExploreConsultationVisibility(false)
// VERIFICATION
verify {
mockViewModel.filterBy(ConsultationTopicsArea.ALL)
}
}
I am getting this error
Related
I have this class that exposes remote configs to others. I thought by creating a class, I would just mock it when testing others that use it but so far, firebase is blocking me. Not sure what I am doing wrong exactly.
class AppRemoteConfig #Inject constructor() {
private var remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig
private fun setListeningInterval(): Long {
if (BuildConfig.DEBUG){
return 0;
}
return 86400;
}
init {
val configSettings = remoteConfigSettings {
minimumFetchIntervalInSeconds = setListeningInterval()
}
remoteConfig.setConfigSettingsAsync(configSettings)
remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
remoteConfig.fetchAndActivate()
.addOnCompleteListener(OnCompleteListener{
if (it.isSuccessful) {
remoteConfig.activate()
}
})
}
fun getString(key: String): String {
return this.remoteConfig.getString(key)
}
}
Now a class uses it this way:
class GetRData #Inject constructor(
private val _remoteConfig: AppRemoteConfig
) {
operator fun invoke(key): String {
try {
return _remoteConfig.getString(key)
} catch(ex: Exception){
return ""
}
return ""
}
}
Now I want to test GetRData class but I get the error: Default FirebaseApp is not initialized in this process null. Make sure to call FirebaseApp.initializeApp(Context) first.
here is what I have tried:
class GetRDataTest {
private var appRemoteConfig = mockk<AppRemoteConfig>(relaxed = true)
private lateinit var getRData : GetRData
#Before
fun setUp(){
getRData = GetRData(appRemoteConfig)
}
#Test
fun `Should get string value`() {
every { appRemoteConfig.getString("status") } returns "red"
val result = getRData.invoke("status")
verify { appRemoteConfig.getString("status") }
Truth.assertThat(result).isEqualTo("red")
}
}
I have a problem with the following code snippet:
(Some functions' bodies are ommited for clear view)
fun collectLinks(page: Page): List<String> {
return LinksCrawler().run {
page.accept(this)
this.links
}
}
class LinksCrawler {
private var _links = mutableListOf<String>()
val links
get() = _links.toList()
fun visit(page: Page) { (...) }
fun visit(container: Container) = { (...) }
private fun visit(elements: List<HtmlElement>){ (...) }
}
When I invoke collectLinks() I get
Visitor$LinksCrawler: method 'void ()' not found
(where Visitor is my filename)
As far as I believe, problem would be caused by scope function .run(), maybe that it has no initialisation code that would do sth with LinksCrawler, but correct me if I am wrong.
I do it in .kts file, if it has any meaning. In overall, it is supposed to be an example for a Visitor design pattern. Full file code below:
import Visitor.HtmlElement.Image as Image
import Visitor.HtmlElement.Link as Link
import Visitor.HtmlElement.Table as Table
import Visitor.HtmlElement.Container as Container
main()
// ---------------
fun main() {
val page = Page(Container(Image(), Link(), Image()),
Table(),
Link(),
Container(Table(), Link()),
Container(Image(), Container(Image(), Link())))
println(collectLinks(page))
}
fun collectLinks(page: Page): List<String> {
return LinksCrawler().run {
page.accept(this)
this.links
}
}
class LinksCrawler {
private var _links = mutableListOf<String>()
val links
get() = _links.toList()
fun visit(page: Page) {
visit(page.elements)
}
fun visit(container: Container) = visit(container.elements)
private fun visit(elements: List<HtmlElement>){
for (e in elements) {
when (e) {
is Container -> e.accept(this)
is Link -> _links.add(e.href)
is Image -> _links.add(e.src)
else -> {}
}
}
}
}
fun Container.accept(feature: LinksCrawler) {
feature.visit(this)
}
fun Page.accept(feature: LinksCrawler) = feature.visit(this)
class Page(val elements: MutableList<HtmlElement> = mutableListOf()) {
constructor(vararg elements: HtmlElement) : this(mutableListOf()) {
for (s in elements) {
this.elements.add(s)
}
}
}
sealed class HtmlElement {
class Container(val elements: MutableList<HtmlElement> = mutableListOf()) : HtmlElement() {
constructor(vararg units: HtmlElement) : this(mutableListOf()) {
for (u in units) {
this.elements.add(u)
}
}
}
class Image : HtmlElement() {
val src: String
get() = "http://image"
}
class Link : HtmlElement() {
val href : String
get() = "http://link"
}
class Table : HtmlElement()
}
I have a case where the unit of code I'm testing is running on a different thread and so the test executes and fails before the unit has finished executing:
class Tests {
private lateinit var result: String
#BeforeAll
fun setup() {
DataService().subscribe {
result = it
}
}
#Test
fun `get result from data service`() {
assert(result.contains("Hello"))
}
}
When the test runs, I get the following exception:
kotlin.UninitializedPropertyAccessException: lateinit property result has not been initialized
How can I ensure that the tests don't run before result has been initialized?
The test in the provided form won't work: #BeforeAll is allowed only on static methods, but then it couldn't access the result field. It can be solved by using #BeforeEach and #TestInstance(TestInstance.Lifecycle.PER_METHOD) [but see the UPDATE at the end of the post]
Regarding the result initialization itself: you can check if it has been initialized using this::result.isInitialized, e.g.:
#TestInstance(TestInstance.Lifecycle.PER_METHOD)
class AwaitTest {
private lateinit var result: String
#BeforeEach
fun setup() {
DataService().subscribe {
result = it
}
}
#Test
fun `get result from data service`() = runBlocking {
awaitInitialization()
assert(result.contains("Hello"))
}
suspend fun awaitInitialization() {
while(!this::result.isInitialized) {
delay(100)
}
}
}
Alternatively you could use awaitility:
#TestInstance(TestInstance.Lifecycle.PER_METHOD)
class AwaitTest {
private lateinit var result: String
#BeforeEach
fun setup() {
DataService().subscribe {
result = it
}
}
#Test
fun `get result from data service`() {
await until { this#AwaitTest::result.isInitialized }
assert(result.contains("Hello"))
}
}
Or even better, move await to the setup() method:
#TestInstance(TestInstance.Lifecycle.PER_METHOD)
class AwaitTest {
private lateinit var result: String
#BeforeEach
fun setup() {
DataService().subscribe {
result = it
}
await until { this#AwaitTest::result.isInitialized }
}
#Test
fun `get result from data service`() {
assert(result.contains("Hello"))
}
}
UPDATE:
Actually a #BeforeAll method doesn't need to be static if the test class is annotated with the#TestInstance(TestInstance.Lifecycle.PER_CLASS):
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
class AwaitTest {
private lateinit var result: String
#BeforeAll
fun setup() {
DataService().subscribe {
result = it
}
await until { this#AwaitTest::result.isInitialized }
}
#Test
fun `get result from data service`() {
assert(result.contains("Hello"))
}
}
I am trying to test the getTopicNames function (below) in two scenarios: If it succeeds and if it does not succeed.
fun getTopicNames(): Either<Exception, Set<String>> =
try {
adminClient.listTopics()
.names()
.get()
.right()
} catch (exception: ExecutionException) {
exception.left()
}
This is the test class in which I am doing those two scenarios. If I run each test individually, they both suceed. If I run the entire class the second to execute fails because for some reason the previous mock on adminClient.listTopics() is being retained.
These are the versions for everything involved:
kotlin: 1.3.72
koin: 2.1.6
junit: 5.6.1
mockk: 1.10.0
class TopicOperationsTest {
#BeforeEach
fun start() {
val testModule = module(createdAtStart = true) {
single { mockk<AdminClient>() }
}
startKoin { modules(testModule) }
}
#AfterEach
fun stop() {
stopKoin()
}
#Test
fun `getTopicNames() returns a Right with the topics names`() {
val adminClient = get(AdminClient::class.java)
val listOfTopicsToReturn = mockk<ListTopicsResult>()
val expectedTopics = setOf("Topic1", "Topic2", "Topic3")
every { adminClient.listTopics() } returns listOfTopicsToReturn
every { listOfTopicsToReturn.names() } returns KafkaFuture.completedFuture(expectedTopics)
println("listOfTopicsToReturn.names(): " + listOfTopicsToReturn.names())
println("adminClient.listTopics(): " + adminClient.listTopics())
println("getTopicNames(): " + getTopicNames())
assertThat(getTopicNames().getOrElse { emptySet() }, `is`(expectedTopics))
}
#Test
fun `getTopicNames() returns a Left if failing to get topic names`() {
val adminClient = get(AdminClient::class.java)
every { adminClient.listTopics() } throws ExecutionException("Some Failure", Exception())
assertThat(getTopicNames(), IsInstanceOf(Either.Left::class.java))
}
}
This is the error I get, caused by the fact that the test that verifies the failure is the first to run:
java.lang.AssertionError:
Expected: is <[Topic1, Topic2, Topic3]>
but: was <[]>
Expected :is <[Topic1, Topic2, Topic3]>
Actual :<[]>
<Click to see difference>
Already tried clearAllMocks() on the BeforeEach method but it does not solve my problem as I just start getting:
io.mockk.MockKException: no answer found for: AdminClient(#1).listTopics()
I found a solution that makes everything work. It is a combination of:
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
Having the mock as a class object
MockKAnnotations.init(this) in the #BeforeEach method
clearMocks() specifying the actual mock to be cleared (should work for multiple mocks too, just separated by commas.
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TopicOperationsTest {
private var adminClientMock = mockk<AdminClient>()
#BeforeEach
fun start() {
MockKAnnotations.init(this)
val testModule = module(createdAtStart = true) {
single { adminClientMock }
}
startKoin { modules(testModule) }
}
#AfterEach
fun stop() {
clearMocks(adminClientMock)
stopKoin()
}
#Test
fun `getTopicNames() returns a Right with the topics names`() {
val adminClient = get(AdminClient::class.java)
val listOfTopicsToReturn = mockk<ListTopicsResult>()
val expectedTopics = setOf("Topic1", "Topic2", "Topic3")
every { adminClient.listTopics() } returns listOfTopicsToReturn
every { listOfTopicsToReturn.names() } returns KafkaFuture.completedFuture(expectedTopics)
assertThat(getTopicNames().getOrElse { emptySet() }, `is`(expectedTopics))
}
#Test
fun `getTopicNames() returns a Left if failing to get topic names`() {
val adminClient = get(AdminClient::class.java)
every { adminClient.listTopics() } throws ExecutionException("Some Failure", Exception())
assertThat(getTopicNames(), IsInstanceOf(Either.Left::class.java))
}
}
Given
typealias MyCallback = (s: String) -> Unit
object Hello {
fun main() {
blah { print(it) }
}
fun blah(cb: MyCallback) {
cb.invoke("hi")
}
}
Or
interface MyCallback {
fun invoke (s: String) {}
}
object Hello {
fun main() {
blah(object : MyCallback {
override fun invoke(s: String) {
print(s)
}
})
}
fun blah(cb: MyCallback) {
cb.invoke("hi")
}
}
With both I get the above error (Verification failed: call 1 of 1: MyCallback(#2).invoke(any())) was not called) when doing
#Test
fun testInvoke() {
val mock = mockk<Hello>(relaxed = true)
val cb = mockk<MyCallback>()
mock.blah(cb)
verify { cb.invoke(any()) }
}
how to fix it?
This worked for me. The Hello object doesn't need to be mocked since it is the class being tested. By mocking it, the test was only recording invocations of blah() rather than actually executing them.
Using spyk rather than mockk allows the MyCallback type to be constructed allowing the invoke() function to be defined. So maybe that's more of a workaround than an explanation of why mockk doesn't seem to retain that type info.
typealias MyCallback = (s: String) -> Unit
object Hello {
fun main() {
blah { print(it) }
}
fun blah(cb: MyCallback) {
cb.invoke("hi")
}
}
class MockKTest {
#Test
fun testInvoke() {
val mock = spyk<Hello>()
val cb = mockk<MyCallback>(relaxed = true)
mock.blah(cb) // or just do Hello.blah(cb)
verify { cb.invoke(any()) }
}
}