简体   繁体   中英

KMM-MockK: Cannot mock the expect object class when I write the unit test case

As the title says, currently I'm having issues using mockk when writing unit tests in commonTest in my KMM project.

In my shared module, I created a useCase class that uses the expected object class to do things like read and write files. But when I follow the guide book(https://notwoods.github.io/mockk-guidebook/docs/mocking/static/ ) to mock the read and write operations, according to the debug result, it does not seem to excute the result of my mock instead of excuting the real operation.

The part of the use case class:

class UseCase {
  fun needToTest{
    ...
   if(FileOperation.mvFile(scr,dest)){
    ...
   }
    ...
}
}

The example file operation class:

  expect object FileOperation {
    
    fun rdFile(path: String): List<Path>?
   
    fun mvFile(srcPath: String, destPath: String): Boolean?
     ....
  }

android Part

  actual object FileOperation {
       ......
     actual fun mvFile(srcPath:String, destPath: String): Boolean? {
       ......
     }
      .......
  }

ios part

   actual object FileOperation {
   .......
   .......
}

The example mockk method what I used currently

val useCaseTest = mock<UseCase>()
mockkObject(FileOperation)
every{ FileOperation.mvFile(srcPathMock, any())} returns true
when{
  useCaseTest.needToTest()
}

The dependency in the build.gradle of shared module:

  implementation("io.mockk:mockk-common:1.12.2")

You can separate the dependencis of MockK. I have used this for commonTest :

val commonTest by getting {
   dependencies {
      implementation(kotlin("test"))
      implementation("io.insert-koin:koin-test:$koinVersion")
      implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4")
      implementation("io.mockk:mockk-common:1.12.1") //<== THIS FOR MOCKK
   }
}

And this one for androidTest :

val androidTest by getting {
   dependencies {
      // without this, it cannot find "every", "any" and some other functions
      implementation("io.mockk:mockk-jvm:1.13.2")
   }
}

When you run the tests from Android Studio and JVM you are ready to go, but you need more stuff to be added to run them for iOS. Unfortunately, I have no solution for iOS at the time of this writing.

You can find this solution in my sample project .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM