无法模拟方法

时间:2017-01-16 07:35:56

标签: junit mocking mockito powermockito

我是JUNITS的新手并且一直在尝试使用Mockito和PowerMockito为我的代码编写一些测试用例,但一直面临着一个问题。

班级代码:

public class Example implements Callable<Void> {
    int startIndex;
    int endIndex;
    ConnectionPool connPool;
    Properties properties;

    public Example(int start, int end,
           ConnectionPool connPool, Properties properties) {
        this.startIndex = start;
        this.endIndex = end;
        this.connPool= connPool;
        this.properties = properties;
    }

    @Override
    public Void call() throws Exception {
        long startTime = System.currentTimeMillis();
        try {

            List<String> listInput = new ArrayList<>();
            Service service = new Service(
                    dbConnPool, properties, startIndex, endIndex);

            service.getMethod(listInput);

            .
            .
            .

JUNIT代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest()
public class ExampleTest {

    @Mock
    private ConnectionPool connectionPool;

    @Mock
    private Properties properties;

    @Mock
    private Service service = new Service(
            connectionPool, properties, 1, 1);

    @Mock
    private Connection connection;

    @Mock
    private Statement statement;

    @Mock
    private ResultSet resultSet;

    @InjectMocks
    private Example example = new Example(
            1, 1, connectionPool, properties);


    @Test
    public void testCall() throws Exception {
        List<String> listInput= new ArrayList<>();
        listInput.add("data1");

        when(service.getMethod(listInput)).thenReturn(listInput);
        example.call();
    }

问题:如何模拟Service类及其方法getMethod,调用?

说明:Service类具有getMethod方法,该方法与DB交互。所以,因为我无法模拟这个方法,代码会通过,然后我必须将getMethod中的所有对象模拟为连接,结果集等。否则它会抛出NullPointerException。

请帮助我理解我做错了什么,并且如果可能的话,就我应该接近JUNITS进行这种方法调用的方式提供指导。

1 个答案:

答案 0 :(得分:0)

如果您在方法中调用new Service,Mockito将无法帮助您模拟对象。 相反,您需要使用PowerMock.expectNew

Service mockService = PowerMock.createMock(Service.class);
PowerMock.expectNew(Service.class, connectionPool, properties, 1, 1)
         .andReturn(mockService);

PowerMock.replay(mockService);

对于PowerMockito,有一个等价物:

PowerMockito.whenNew(Service.class)
            .withArguments(connectionPool, properties, 1, 1)
            .thenReturn(mockService);

请检查this article