预期会引发java.lang.IllegalArgumentException,但未引发任何事件

我正在模拟和Junit 5中为在File Utility类的伴随对象中定义的静态方法编写单元测试用例。

方法如下

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
        }
    }

}

单元测试用例如下,

@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}
}

收到以下错误,

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
评论
  • 九尾狐
    九尾狐 回复

    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}
    }