【问题标题】:Partial mocking a method of a subclass makes it bypass the superclass constructor部分模拟子类的方法使其绕过超类构造函数
【发布时间】:2016-03-06 17:34:01
【问题描述】:

我试图仅模拟一个扩展另一个 (Person) 的类 (Collaborator) 的方法 (getValue)。但是,在设置Expectations 块后,调用此方法时,模拟类的构造函数不会执行super(...)

以下示例改编自此处显示的代码:http://jmockit.org/tutorial/Mocking.html#partial

问题发生在对象Collaborator c3 上。最后一个assert 失败了,我希望它会通过。

public class PartialMockingTest
{
   static class Person
   {
      final int id;

      Person() { this.id = -1; }
      Person(int id) { this.id = id; }

      int getId() { return id; }
   }          

   static class Collaborator extends Person
   {
       final int value;

       Collaborator() { value = -1; }
       Collaborator(int value) { this.value = value; }
       Collaborator(int value, int id) { super(id); this.value = value; }

       int getValue() { return value; }
       final boolean simpleOperation(int a, String b, Date c) { return true; }
   }

   @Test
   public void partiallyMockingAClassAndItsInstances()
   {
      final Collaborator anyInstance = new Collaborator();

      new Expectations(Collaborator.class) {{
         anyInstance.getValue(); result = 123;
      }};

      // Not mocked, as no constructor expectations were recorded:
      Collaborator c1 = new Collaborator();
      Collaborator c2 = new Collaborator(150);
      Collaborator c3 = new Collaborator(150, 20); 

      // Mocked, as a matching method expectation was recorded:
      assertEquals(123, c1.getValue());
      assertEquals(123, c2.getValue());
      assertEquals(123, c3.getValue());

      // Not mocked:
      assertTrue(c1.simpleOperation(1, "b", null));
      assertEquals(45, new Collaborator(45).value);
      assertEquals(20, c3.getId()); // java.lang.AssertionError: expected:<20> but was:<-1>
   }

}

我做错了吗?是bug吗?

【问题讨论】:

    标签: java unit-testing junit mocking jmockit


    【解决方案1】:

    我不是很精通Expectations系统的内部结构,但是在调试了代码之后,我意识到在构造对象之前声明的expectations会弄乱构造函数' 调用。

    这样,如果你在构造之后移动期望,测试应该通过

    final Collaborator anyInstance = new Collaborator();
    
    // Not mocked, as no constructor expectations were recorded:
    Collaborator c1 = new Collaborator();
    Collaborator c2 = new Collaborator(150);
    Collaborator c3 = new Collaborator(150, 20);
    
    new Expectations(Collaborator.class) {{
       anyInstance.getValue(); result = 123;
    }};
    
    // Mocked, as a matching method expectation was recorded:
    assertEquals(123, c1.getValue());
    assertEquals(123, c2.getValue());
    assertEquals(123, c3.getValue());
    
    // Not mocked:
    assertTrue(c1.simpleOperation(1, "b", null));
    assertEquals(45, new Collaborator(45).value);
    assertEquals(20, c3.getId());  //it works now
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多