java - 在删除文件内容之前创建单元测试

标签 java unit-testing junit mockito

我有以下 JAVA 代码:

@Override
public void myFunc(...) {
   String content = createFileContent(...);
   File f = createFile(content);
   uploadFile(f);
   deleteFile(f)
}

我想使用单元测试来测试文件内容或文件本身(两者都可以工作)。 该文件在函数结束之前被删除。 您建议在这里采取什么方法? (我使用 Mockito 作为模拟框架)

最佳答案

监视目标测试类并定义行为并验证方法的调用,如果您想断言参数,可以使用ArgumentCaptor

public class TargetTest {

    @Test
    public void shouldDoSomething() {
        // Arrange
        final String content = "content-file";
        final File file = new File();
        Target target = spy(target);
        doReturn(content).when(target).createFileContent();
        doReturn(file).when(target).createFile(content);
        doNothing().when(target).uploadFile(file);
        doNothing().when(target).deleteFile(file);

        // Act
        target.myFunc();

       // Assert
        verify(target).createFileContent();
        verify(target).createFile(content);
        verify(target).uploadFile(file);
        verify(target).deleteFile(file);
    }
}

关于java - 在删除文件内容之前创建单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62267388/

相关文章:

java - 使用 JUnit 作为验收测试框架

java - Spring Kafka - 动态创建流

java - 如何使用工厂子类中的子类来覆盖父类(super class)工厂中的抽象类?

angular - 您如何在 ngOnInit 生命周期中测试可观察对象?

unit-testing - 当方法中的代码被 emma 覆盖时,为什么方法调用显示为未覆盖?

spring - 具有 Spring 应用程序上下文的 JUnit 自定义运行器

java - 多个版本的 javamail jar 导致 NoSuchProviderException

javascript - javascript上的多线程捕获子线程的响应

unit-testing - 自动 "test"故事书

PHPUnit:使用来自父类的测试来测试依赖关系