2012-04-16 69 views
0

我有問題與嘲諷oracles ArrayDescriptor。下面是一個代碼示例: 讓說,我有方法是這樣的PowerMock和嘲諷oracle ArrayDescriptor

public void doSomething(){ 
    //some code here 
    ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("TEST", connection); 
    //some more code 
    } 

我應該怎樣嘲笑那arrayDescriptor一部分? 我想是這樣的:

PowerMock.mockStatic(ArrayDescriptor.class); 
//connection is mocked 
ArrayDescriptor arrayDescriptor = Mockito.mock(ArrayDescriptor.class); 
//connection is also mocked 
Mockito.when(ArrayDescriptor.createDescriptor("TEST", connection).thenReturn(arrayDescriptor); 

但是,這並不工作,拋出某種NullPointerException異常有關SQLName,我試圖嘲弄SQLName,但並沒有幫助。

希望有人能幫助:)

回答

0

移動調用ArrayDescriptor.createDescriptor(...)關進了自己的類的單行法(可以是一個內部類,你使用它在類的)。將字段添加到您使用此調用的類中,該調用具有新類的實例。使用setter或特殊構造函數將該字段設置爲與通常不同的值。然後嘲笑內心階層,並讓它返回ArrayDescriptor的模擬。所以你可能會得到這樣的東西。

public class MyClass{ 

    class ArrayDescriptorFactory{ 
     makeArrayDescriptor(String name, Connection connection){ 
      return ArrayDescriptor.createDescriptor(name, connection); 
     } 
    } 

    private ArrayDescriptorFactory factory; 

    public MyClass(){ 
     this(new ArrayDescriptorFactory()); 
    } 

    MyClass(ArrayDescriptorFactory factory){ 
     this.factory = factory; 
    } 

    public void doSomething(){ 
     ... do stuff ... 
     factory.makeArrayDescriptor("something", someConnection); 
     ... do more stuff ... 
    } 
} 

,並在測試

@Mock private MyClass.ArrayDescriptorFactory mockFactory; 
@Mock private ArrayDescriptor mockArrayDescriptor; 

... 

initMocks(this); 
when(mockFactory.makeArrayDescriptor(anyString(), any(Connection.class))) 
.thenReturn(mockArrayDescriptor); 
MyClass toTest = new MyClass(mockFactory);