使用Mockito测试具有lambda参数的方法的链式调用

时间:2018-08-21 18:23:49

标签: java unit-testing mocking mockito

我有以下界面:

DAOFunctionCommand:

@FunctionalInterface
public interface DAOFunctionCommand<T, R>
{
    R execute(T input, IDAOManager manager) throws Exception;
}

DAOSupplierCommand:

@FunctionalInterface
public interface DAOSupplierCommand<T>
{
    T get(IDAOManager manager) throws Exception;
}

ITransactionStream:

public interface ITransactionStream<T, K extends IDAOManager>
{
    <R> ITransactionStream<R, K> chain(DAOFunctionCommand<? super T, ? extends R> cmd) throws Exception;

    <R> ITransactionStream<R, K> chain(DAOSupplierCommand<? extends R> cmd) throws Exception;

    T getResult();

    T end() throws Exception;
}

ITransactionHead:

public interface ITransactionHead<T, K extends IDAOManager>
{
    ITransactionStream<T, K> start() throws Exception;
}

IDAOManager:

public interface IDAOManager
{
    ITicketDAO getTicketDAO() throws Exception;

    IParkingSpotsDAO getParkingSpotDAO() throws Exception;

    IParkingSpotCategoriesDAO getParkingSpotCategoriesDAO() throws Exception;

    ITransactionHead<Object, ? extends IDAOManager> txStream() throws Exception;
}

在代码中的某处使用IDAOManager就像这样:

public Optional<ParkingSpot> occupySpot(String category) throws Exception
{
    daoManager.getParkingSpotCategoriesDAO().get(category);

    Optional<ParkingSpot> ps = daoManager.txStream()
            .start()
            .chain((m) -> m.getParkingSpotDAO().getFreeSpot(category))
            .chain((p, m) ->
            {
                if (!p.isPresent()) return Optional.<ParkingSpot>empty();
                p.get().setAvailable(false);
                m.getParkingSpotDAO().update(p.get());
                return p;
            }).end();

    if (ps.isPresent()) notifyAllListeners();
    return ps;
}

可以模拟链接的呼叫吗?

假设:m.getParkingSpotDAO().getFreeSpot(category)始终返回非空的Optional<ParkingSpot>

谢谢。

0 个答案:

没有答案