我有一个像这样的 kotlin 代码:
internal fun doA() {
var file: File? = null
try {
// do something
file = fileCreator.create()
} catch (e: IOException) {
throw e
} finally {
if (file.exists()) {
file.delete()
}
}
}
如何编写一个单元测试来验证上面的
file.delete()
行是否运行?
为了实现这一点,您可以结合使用模拟对象和 Mockito 等测试框架提供的验证。以下是编写此类单元测试的方法:
exists()
方法返回true,从而执行删除逻辑。delete()
。以下是测试的基本示例:
import org.junit.Test
import org.mockito.Mockito.*
class YourClassTest {
@Test
fun testFileDeletion() {
// Mock the File class
val mockFile: File = mock(File::class.java)
// Stub the exists method to return true
`when`(mockFile.exists()).thenReturn(true)
// Assuming fileCreator is accessible and can be mocked
val mockFileCreator: FileCreator = mock(FileCreator::class.java)
`when`(mockFileCreator.create()).thenReturn(mockFile)
// Inject mockFileCreator into the class containing doA (or directly if possible)
val yourClass = YourClass(mockFileCreator)
// Execute the method under test
yourClass.doA()
// Verify delete was called
verify(mockFile).delete()
}
}