我试图单元测试一个类,其中一个方法返回一个协作者类的实例:根据其参数的值,它返回一个新创建的实例,或者一个保存的,先前创建的实例.
我在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.LLC
最佳答案 将@Mocked注释更改为@Capturing,如下所示:
@Capturing
Collaborator collaborator;
这允许测试通过我.
在我看来,这有点巫毒魔法,但如果您想阅读更多内容,请参阅JMockit教程中的Capturing internal instances of mocked types.
另见Using JMockit to return actual instance from mocked constructor