3

I am writing unit test case in mockk and Junit5 for a static method defined in companion object of FileUtility class.

the method is as below,

class FileUtility {

    companion object {
        fun getFileObject(fileName: String): File {
            require(!StringUtils.isBlank(fileName)) { "Expecting a valid filePath" }
            val file = File(fileName)
            if (file.isHidden)
                throw llegalArgumentException()
            return file
        }
    }

}

the unit test case is as below,

@Test
fun `get file object test throws exception when file path is hidden`() {
    val filePath = "filepath"
    val file = mockk<File>()
    every { file.isHidden } returns true
    assertThrows(IllegalArgumentException::class.java) {
        getFileObject(filePath)
    }
    verify { file.isHidden}
}

getting the following error,

Expected java.lang.Exception to be thrown, but nothing was thrown.

Also, the verify { file.isHidden} line is not working, its giving the following error.

java.lang.AssertionError: Verification failed: call 1 of 1: File(#1).isHidden()) was not called
Laurence
  • 1,556
  • 10
  • 13
Akash Patel
  • 189
  • 1
  • 5
  • 13

1 Answers1

6

The function you are testing instantiates its own instance of a File. It is not using the mocked instance you created.

For this type of test you need to mock the constructor so that any instantiated instance of the class is mocked. You can read more here https://mockk.io/#constructor-mocks but here is your example (with a different assertion library):

@Test
fun `get file object test throws exception when file path is hidden`() {
    val filePath = "filepath"
    mockkConstructor(File::class)
    every { anyConstructed<File>().isHidden } returns true
    assertThat{
        getFileObject(filePath)
    }.isFailure().isInstanceOf(IllegalArgumentException::class)
    verify { anyConstructed<File>().isHidden}
}
Laurence
  • 1,556
  • 10
  • 13
  • 1
    this is giving "Exception in thread 'main' java.lang.StackOverflowError" Error. – Akash Patel May 17 '20 at 17:01
  • @AkashPatel - this is how you would use mockk to do what you want to do. But, it seems they have an open bug ticket -> https://github.com/mockk/mockk/issues/205 Some classes it seems run into this stack overflow.... unfortunate. I think until they fix the bug (you could possibly add your own findings to that issue as well) you might be stuck with using something like power mock to mock your constructor. – Laurence May 18 '20 at 05:59
  • The "StackOverflowError" you are facing is probably related to this known issue: https://github.com/mockk/mockk/issues/121 – Dario Fiumicello Jan 07 '21 at 13:56