【问题标题】:Can you mock out method calls in the class you're testing?你能模拟出你正在测试的类中的方法调用吗?
【发布时间】:2012-01-11 20:34:32
【问题描述】:

我正在尝试为我的代码编写 JUnit 测试,但在我的某些方法中调用了其他方法。是否可以模拟这些调用?

例如

s3FileWrite(File file, Status status)
{
  S3 s3         = new S3(file.getName, s3Service)
  String key    = s3.getKey();
  String bucket = s3.getBucket();
  File tmp = new File("tmp/" + s3.getName());

  writeFile(key, bucket, tmp, status); //local method call I want to mock out
}//awsFileWrite

writeFile 方法是我想要模拟出来的,它是我正在测试的类的一部分,但我不知道如何模拟出来。我认为模拟出我正在测试的类,然后将调用添加到我的期望中就可以了,但它仍然会调用该方法。

谁能给我一些关于在这里做什么的建议吗?

编辑:

我的 JMock 代码如下所示:

@Test
public void testS3FileWrite()
{       
    fileName     = context.mock(File.class);
    s3Service    = context.mock(FileDataAccessor.class);
    s3           = context.mock(S3.class);          
    reportWriter = context.mock(ReportWriter.class); 

    try
    {
        context.checking(new Expectations(){{           
            oneOf(fileMetaData).getKey();
            will(returnValue("s3Key")); 

            oneOf(fileMetaData).getBucketName();
            will(returnValue("BucketName"));

            oneOf(fileMetaData).getName();
            will(returnValue("TempFile"));  

            ((MethodClause) oneOf (any(File.class))).method("File").with(same("tmp/TempFile")); 

            oneOf(reportWriter).writeFile(with(same("s3Key")),
                                   with(same("BucketName")), 
                                   with(any(File.class), 
                                   with(same(Status.OK)));
        }});//Expectations
    }
    catch (Exception e)
    {
        ErrorStatus.debug("Exception in ReportTest.testS3FileWrite: " + e);
    }//try-catch  

    ReportWriter test = new ReportWriter(status);
    test.awsFileWrite(fileName, Status.OK);
}//testAWSFileWrite

【问题讨论】:

  • 您能否发布任何模拟类并定义writeFile() 的预期结果的代码?

标签: java testing jmock


【解决方案1】:

PowerMock 允许您部分模拟类,但它是为 EasyMock 而不是 JMock 设计的。无论如何,这不是最好的方法。

添加一个新类FileWriter 并将writeFile 方法移动到它,然后在您的测试类中, 委托给一个人:

// default implementation, can be replaced in tests
FileWriter fileWriter = new FileWriter();

writeFile(key, bucket, tmp, status) {
    fileWriter.write(key, bucket, tmp, status);
}; 

在您的测试代码中,使用模拟 FileWriter 覆盖被测类中的 fileWriter 字段(添加设置器或使字段受保护)。

【讨论】:

  • 酷 :) 我已将其添加为内部类,以防止代码过度分离...干杯 artbristol
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多