0

i am new to kotlin, junit5 and mockk. i am writing unit test cases for a function which belongs to companion object of a class. how to write unit test cases for this.

class CommonUtility {

    companion object {
        @Throws(SecurityException::class)
        fun initializeFilePath(filePath: String) {
            val directory = File(filePath)
            if (!directory.exists()) {
                try {
                    directory.mkdir()
                } catch (ex: SecurityException) {
                    throw SecurityException("$filePath was not created in system", ex)
                }
                log.info("Created the directory $filePath")
            }
        }
     }
}

can anyone give me one example of unit test that can be written for this function.

Akash Patel
  • 189
  • 1
  • 5
  • 13
  • Does this answer your question? [Unit Testing verifying a companion object method is called (mocking a companion object)](https://stackoverflow.com/questions/53174839/unit-testing-verifying-a-companion-object-method-is-called-mocking-a-companion) – timekeeper May 25 '20 at 20:27

1 Answers1

1

What should you test here?

  • Creating directory with the given file path.
  • Check that nothing happened when the directory already exists.
  • Check that security exception was thrown at the right place and contain a meaningful message.

Example test (first bullet):

@Test
fun `should create directory with given file path`() {
    CommonUtility.initializeFilePath("file")

    val createdFile = File("file")
    assertTrue(createdFile.exists())

    createdFile.delete() // you have to remove directory after test
}

I would recommend changing the name of the method, for example to createDirectoryWithGiven, the current name is not meaningful. It is also a good practice to return what you created in this method, then your method will be easier to test.

Ice
  • 1,783
  • 4
  • 26
  • 52
  • thanks for the answer, it is really helpful for writing UTs. – Akash Patel May 26 '20 at 07:14
  • I have one doubt, how to check for security exception here? @Test fun `check for exception`() { val createdFile = File("file") every { createdFile.mkdir() } throws SecurityException() assertThrows(SecurityException::class.java) { CommonUtility.initializeFilePath("file") } }. i wrote this but giving error – Akash Patel May 26 '20 at 07:23
  • Missing calls inside every { ... } block. – Akash Patel May 26 '20 at 07:24
  • It isn't working because you didn't pass your mocked file to your method. Take a look into your method `val directory = File(filePath)`, here you are creating a new instance of the file. In your case the best option is to rewrite method, instead of having string as an argument, pass there file object, then you can easily mock it. – Ice May 26 '20 at 09:00