EasyMock:无效方法

EasyMock: Void Methods(EasyMock:无效方法)
本文介绍了EasyMock:无效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个方法在一个类中返回 void,该类是我要测试的类的依赖项.

I have a method that returns void in a class that is a dependency of the class I want to test.

这个类很大,我只使用其中的一个方法.我需要为测试替换此方法的实现,因为我希望它做一些不同的事情,并且我需要能够访问此方法接收的参数.

This class is huge and I'm only using this single method from it. I need to replace the implementation of this method for the test as I want it to do something different and I need to be able to access the parameters this method receives.

我在 EasyMock 中找不到这样做的方法.我想我知道如何使用 Mockito 通过使用 doAnswer 但除非绝对必要,否则我不想添加另一个库.

I cannot find a way of doing this in EasyMock. I think I know how to do it with Mockito by using doAnswer but I don't want to add another library unless absolutely necessary.

推荐答案

如果我理解你想做什么正确,你应该可以使用 andAnswer():

If I understand what you want to do correctly, you should be able to use andAnswer():

mockObject.someMethod(eq(param1), eq(param2));
expectLastCall().andAnswer(new IAnswer() {
    public Object answer() {
        //supply your mock implementation here...
        SomeClass arg1 = (SomeClass) getCurrentArguments()[0];
        AnotherClass arg2 = (AnotherClass) getCurrentArguments()[1];
        arg1.doSomething(blah);
        //return the value to be returned by the method (null for void)
        return null;
    }
});

EasyMock 用户指南解释道:

有时我们希望我们的模拟对象返回一个值或抛出一个在实际调用时创建的异常.从 EasyMock 2.2 开始,expectLastCall()expect(T 值) 提供方法 andAnswer(IAnswer answer) 允许 [you] 指定接口的实现 IAnswer 用于创建返回值或异常.

Creating Return Values or Exceptions

Sometimes we would like our mock object to return a value or throw an exception that is created at the time of the actual call. Since EasyMock 2.2, the object returned by expectLastCall() and expect(T value) provides the method andAnswer(IAnswer answer) which allows [you] to specify an implementation of the interface IAnswer that is used to create the return value or exception.

IAnswer 回调中,参数传递给模拟调用可以通过 EasyMock.getCurrentArguments().如果你使用这些,像重新排序参数这样的重构可能会破坏你的测试.您已收到警告.

Inside an IAnswer callback, the arguments passed to the mock call are available via EasyMock.getCurrentArguments(). If you use these, refactorings like reordering parameters may break your tests. You have been warned.

这篇关于EasyMock:无效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)