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