5

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

我在 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);
    }
}

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

提前致谢,

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

4

1 回答 1

3

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

@Capturing
Collaborator collaborator;

这允许我通过测试。

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

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

于 2013-05-16T16:13:50.873 回答