0

我有嘲笑 oracles 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);

但这不起作用,抛出某种与 SQLName 相关的 nullpointerException,我试图模拟 SQLName,但没有帮助。

希望有人可以提供帮助:)

4

1 回答 1

0

Move the call to ArrayDescriptor.createDescriptor( ... ) off into a one-line method of its own class (which can be an inner class of the class where you're using it). Add a field to the class where you're using this call, that has an instance of the new class. Use either a setter or a special constructor to set this field to a value that's different from the usual one. Then mock the inner class, and have it return a mock of ArrayDescriptor. So you might get something like this.

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 ...
    }
}

and in the test

@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 );
于 2012-04-17T06:47:09.163 回答