jmockit 模拟构造函数未返回预期值

Jim*_*kel 5 junit constructor jmockit testcase

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

我在 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

任何有关此测试失败的原因以及如何使其发挥作用的想法都将不胜感激。

提前致谢,

Jim Renkel 高级技术人员 mFluent, Inc. LLC

Jef*_*son 3

将注释更改@Mocked@Capturing,如下所示:

@Capturing
Collaborator collaborator;
Run Code Online (Sandbox Code Playgroud)

这使得我可以通过测试。

在我看来,这有点巫术,但如果您想阅读更多内容,请查看JMockit 教程中的捕获模拟类型的内部实例。

另请参阅使用 JMockit 从模拟构造函数返回实际实例