2013-05-15 67 views
4

我试图单元测试类,其中它的方法返回一个合作者类的实例:这取决于它的参数值,要么返回一个新创建的实例,或保存的,先前创建的实例。jmockit嘲讽构造函数没有返回预期值

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

我简化了这个下降到以下几点:

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

为什么这个测试失败,以及如何使其工作会BR不胜感激任何想法。

由于提前,

吉姆Renkel 高级技术人员 mFluent公司LLC

回答

1

更改@Mocked注释@Capturing,像这样:

@Capturing 
Collaborator collaborator; 

这允许测试传给我。

在我看来,这是一点点巫术魔法,但如果您想了解更多内容,请参阅JMockit教程中的Capturing internal instances of mocked types

另请参阅Using JMockit to return actual instance from mocked constructor

+0

非常感谢您的帮助! 当我将您的修复程序应用于我的真实测试用例时,它仍然不起作用。但经过一些更深入的挖掘和实验后,我才得以实现。问题是我必须捕获多个结构,所以我必须有多个捕获字段,每个字段都有一个maxInstances = 1属性。 非显而易见,但正如我所说,它的工作原理。 再次,非常感谢您的帮助。 吉姆Renkel 高级技术人员 mFluent公司LLC –

+0

大,很高兴它为你工作。欢迎来到StackOverflow! –

+0

相反,只需使用'@Mocked Collaborator mock'。它会嘲笑班级的所有实例,现在和将来。通常,你应该简单地指定'Collaborator'对象期望的行为;没有必要担心实例,除非您需要来自同一个模拟类的不同实例的不同行为。 –