2015-12-02 102 views
1

我試圖嘲笑擴展另一類(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> 
    } 

} 

我做錯了什麼?這是一個錯誤嗎?

回答

1

我並不十分熟悉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