【问题标题】:Junit using Mock ObjectsJunit 使用模拟对象
【发布时间】:2013-11-26 08:03:24
【问题描述】:
MyClass{

public void myfunction(){
AnotherClass c=new AnotherClass();
c.somethod();//This method sets some values of the AnotherClass object c;

}
}

我有上面的场景要测试。如何检查AnotherClass对象c的值是否设置正确。我知道我必须使用Mock Objects对于这些。但是由于上述设计,我无法将 AnotherClass 的模拟对象传递给 myfunction 。任何人都可以帮助我吗?

【问题讨论】:

  • 尝试测试调用 myfunction() 方法的结果。如果变量 'c' 是方法局部变量,当您调用 c.somethod() 时会发生什么?什么是外部可观察的结果?
  • 结果无法从外部获取。 c.somemethod() 正在设置在 myfunction() 中创建的 c 的值
  • 您应该对以某种形式提供给外部的功能进行单元测试。如果做 c.somethod() 没有做任何外部可见的事情,那么恕我直言,你不需要对它进行单元测试
  • 我同意@DevBlanked,您应该只尝试测试外部可见的内容。我猜您的示例是示例代码,因此缺少一些可能使其可测试的实现细节。例如,如果c 被传递给其他一些可模拟对象,则可以使用捕获并且可以断言c 的值。如果做不到这一点,如果您真的想知道是否调用了 somethod 或者是否更改了 c,则需要重新设计。

标签: junit4 easymock


【解决方案1】:

如果你真的想这样做,应该像下面这样重新设计(正如 Dan 也建议的那样)

import org.junit.Test;
import org.mockito.Mockito;

public class TestingMock {

    @Test
    public void test() {
        MyClass target = Mockito.spy(new MyClass());
        AnotherClass anotherClassValue = Mockito.spy(new AnotherClass());
        Mockito.when(target.createInstance()).thenReturn(anotherClassValue);
        target.myfunction();
        Mockito.verify(anotherClassValue).somethod();
    }

    public static class MyClass {

        public void myfunction(){
            AnotherClass c = createInstance();
            c.somethod();//This method sets some values of the AnotherClass object c;
        }

        protected AnotherClass createInstance() {
            return new AnotherClass();
        }
    }

    public static class AnotherClass {

        public void somethod() {

        }

    }
}

您会看到注释掉 c.somethod() 会使测试失败。 我正在使用 Mockito。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2022-11-01
    • 2021-01-03
    相关资源
    最近更新 更多