java - 为单元测试模拟java对象

标签 java unit-testing mocking

我正在寻找一个好的单元测试框架,我可以使用它来模拟可以在 JDK 1.4.2 下运行的私有(private)方法。

干杯,

最佳答案

尝试 Mockito你会爱上它的!

您可以在这个 blog post 中查看此库,显示了 Mockito 用法的 6 个简单示例。

一个简短的例子:

@Test
public void iteratorWillReturnHelloWorld(){
    //arrange
    Iterator i = mock(Iterator.class);
    when(i.next()).thenReturn("Hello").thenReturn("World");
    //act
    String result = i.next() + " " + i.next();
    //assert
    assertEquals("Hello World", result);
}

根据您的要求进行编辑:

看来 Mockito 在 Java 1.4 和 JUnit 3 上运行得很好,如 blog post 中所述.

与上面相同的示例,但针对 Java 1.4:

public void testIteratorWillReturnHelloWorld(){
    //arrange
    Iterator i = Mockito.mock(Iterator.class);
    Mockito.when(i.next()).thenReturn("Hello").thenReturn("World");
    //act
    String result = i.next() + " " + i.next();
    //assert
    assertEquals("Hello World", result);
}

关于java - 为单元测试模拟java对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1635454/

相关文章:

java - 如何在边框内填充组 SWT 小部件的必要详细信息

java - 正则表达式查询Mongodb $和运算符结果问题

perl - 我怎样才能将不同种类的 Perl 测试分开,这样我就不必全部运行它们了?

java - 在 OpenJFX 中使用 SwingNode 出现不满意的链接错误

java - 用于在 Hortonworks 上配置 Storm 拓扑和 kafka 的属性文件

unit-testing - Meteor - 使用测试数据库运行包测试

swift - 对使用 Parse.com 的 Swift 应用程序进行单元测试

python - 在 Python 中模拟标准输出

mocking - WinRT的模拟框架?

java - Mockito Verify 方法如何工作?