简体   繁体   中英

Using mockito for interface implementations

I'm trying to write test a case with mockito for a class that is injected with a ComboPooledDataSource.

I'm got an error saying that ComboPooledDataSource is a final class and cannot be mocked. So, I was thinking of mocking the interface(either DataSource) and using it for the test case but am not sure how to do it.

private Datasource cpds;
private Connection connection;

@Test
public void test() throws Exception {

    connection = getConn();
    cpds = mock(DataSource.class);
    when(cpds.getConnection()).thenReturn(connection);
    accessor = new comboPoolUser(cpds);
    accessor.setConnection();

}

method in comboPoolUser that calls getConnection:

public void setConnection() {

    try {
    connection = comboPooledDataSource.getConnection();
    } catch (SQLException e) {
    throw new RuntimeException("error",e);
    }

}

my "comboPoolUser" constructor takes in a ComboPooledDataSource but I'm trying to mock a "DataSource" for the test so I'm getting a "cannot find symbol: constructor comboPoolUser(javax.sql.DataSource)" error. What's the correct way to do this?

If your ComboPoolUser only requires the methods that are on the DataSource interface, change the constructor so that it takes in a DataSource. Currently the only thing it's doing is getting the connection, so on the face of it it looks possible. Generally, passing dependencies by interface helps maintain encapsulation.

Alternatively, if the ComboPoolUser is your own class, you could write a wrapper around the ComboPoolDataSource, give the wrapper an interface of your own, and make it so think that it's testable by inspection (so every method in the wrapper is just a delegation to the ComboPoolDataSoruce). You can then mock the interface to the wrapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM