在单元测试中断言执行 if 语句

问题描述 投票:0回答:1

我有一个像这样的 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()
行是否运行?

java kotlin unit-testing
1个回答
0
投票

为了实现这一点,您可以结合使用模拟对象和 Mockito 等测试框架提供的验证。以下是编写此类单元测试的方法:

  1. 模拟 File 类:使用 Mockito 创建 File 类的模拟。
  2. Stub方法调用:Stub
    exists()
    方法返回true,从而执行删除逻辑。
  3. 验证方法调用:执行被测方法后,验证是否在模拟 File 对象上调用了
    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()
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.