如何强制Groovy中的方法抛出异常

时间:2012-01-25 20:17:32

标签: testing groovy

我想为Groovy中抛出IOException的方法编写测试。我在测试中模拟这个的唯一方法是强制该方法抛出此异常 这就是原始代码的样子:

    public void cleanUpBermudaFiles(RequestMessage requestMessage)

    {
    final File sourceDirectory = new  File(preferenceService.getPreference("bermuda.landingstrip") + File.separator + requestMessage.getWorkflowId().getValue());

    if(sourceDirectory!=null && sourceDirectory.exists())
    {
         deleteDirectory(sourceDirectory);
    }
    else
    {
        LOG.error("Directory must exist in order to delete");
    }

}

private void deleteDirectory(File directoryToDelete)
{
    try {
        FileUtils.deleteDirectory(directoryToDelete);
    } catch (Exception e) {
        LOG.error("Failed to delete Bermuda files directory located at:" + directoryToDelete.getPath() + "with an exception" + e.getMessage());
    }
}

MY TEST :(我正在寻找一种让deleteDirectory抛出IOException的方法)

     public void testCleanUpBermudaFailure()
    {
    workflowId = new WorkflowId("123456")
    workflowDirectory = new File(srcDirectory, workflowId.value)
    workflowDirectory.mkdir()
    File.createTempFile('foo','.lst', workflowDirectory)
    def exception = {throw new IOException()}

    expect(mockRequestMessage.getWorkflowId()).andReturn(workflowId)
    expect(mockPreferenceService.getPreference("bermuda.landingstrip")).andReturn(srcDirectory.path)
    replay(mockPreferenceService, mockRequestMessage)
    fileCleanUpService.preferenceService = mockPreferenceService
    fileCleanUpService.metaClass.deleteDirectory = exception
    fileCleanUpService.cleanUpBermudaFiles(mockRequestMessage)
    verify(mockPreferenceService, mockRequestMessage)
    assert srcDirectory.listFiles().length == 0, 'CleanUp failed'

}

2 个答案:

答案 0 :(得分:2)

如果服务类是Groovy类,您可能希望模拟FileUtils,如:

FileUtils.metaClass.static.deleteDirectory = { File f -> throw new IOException() }

但是,正如ataylor指出的那样,如果它是Java类,则无法拦截调用。你可以找到一篇关于它的好文章here

答案 1 :(得分:0)

您正在模仿对deleteDirectory的无法调用,但真实的deleteDirectory会使用File类型的一个参数。试试这个:

def exception = { File directoryToDelete -> throw new IOException() }
...
fileCleanUpService.metaClass.deleteDirectory = exception