【问题标题】:jmockit mocked constructor not returning expected valuejmockit 模拟构造函数不返回预期值
【发布时间】:2013-05-15 22:39:07
【问题描述】:

我正在尝试对一个类进行单元测试,其中一个方法返回一个协作者类的实例:根据其参数的值,它要么返回一个新创建的实例,要么返回一个已保存的、以前创建的实例。

我在 Expectations 中模拟构造函数调用,并将结果设置为一个作为协作者模拟实例的值。但是,当我使用导致它创建新实例的参数值测试该方法时,模拟的构造函数以及该方法不会返回预期值。

我已将其简化为以下内容:

package com.mfluent;
import junit.framework.TestCase;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Tested;
import org.junit.Assert;
import org.junit.Test;

public class ConstructorTest extends TestCase {

    static class Collaborator {
    }

    static class ClassUnderTest {
        Collaborator getCollaborator() {
            return new Collaborator();
        }
    }

    @Tested
    ClassUnderTest classUnderTest;

    @Mocked
    Collaborator collaborator;

    @Test
    public void test() {
        new Expectations() {
            {
                new Collaborator();
                result = ConstructorTest.this.collaborator;
            }
        };

        Collaborator collaborator = this.classUnderTest.getCollaborator();
        Assert.assertTrue("incorrect collaborator returned", collaborator == this.collaborator);
    }
}

任何关于此测试失败的原因以及如何使其工作的想法将不胜感激。

提前致谢,

吉姆·伦克尔 高级技术人员 mFluent, Inc. 有限责任公司

【问题讨论】:

    标签: junit constructor testcase jmockit


    【解决方案1】:

    @Mocked注解改成@Capturing,像这样:

    @Capturing
    Collaborator collaborator;
    

    这可以让我通过测试。

    在我看来,这有点像巫术魔法,但如果您想了解更多信息,请查看 JMockit 教程中的 Capturing internal instances of mocked types

    另见Using JMockit to return actual instance from mocked constructor

    【讨论】:

    • 非常感谢您的帮助!当我将您的修复应用到我的真实测试用例时,它仍然不起作用。但经过更多的挖掘和实验,我能够让它工作。问题是我必须捕获多个结构,所以我必须有多个捕获字段,每个字段都有一个 maxInstances = 1 属性。不明显,但正如我所说,它有效。再次,非常感谢您的帮助。 Jim Renkel 高级技术人员 mFluent, Inc. LLC
    • 太好了,很高兴它对你有用。欢迎来到 StackOverflow!
    • 改为尝试使用@Mocked Collaborator mock。它将模拟类的 所有 实例,现在和未来。通常,您应该简单地指定 Collaborator 对象的预期行为;无需担心实例,除非您需要来自同一模拟类的不同实例的不同行为。
    猜你喜欢
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    相关资源
    最近更新 更多