模拟匿名内部类来更改外部本地最终变量

时间:2015-01-23 16:34:30

标签: java unit-testing mockito

我有以下代码片段,其中内部匿名类将更改外部本地最终变量。

我想为这段代码编写统一的测试代码,我可以编写一个测试代理并在其中定义我的callStoredProcedure,虽然我无法弄清楚如何更改外部最终变量,就像匿名类一样有

我正在使用Mockito,任何线索?

        final List<String> result = new ArrayList<String>();

        proxy.callStoredProcedure(param1, param2,
                param3, resolveSQL(param4),
                new IProxyExtractor<GenericDTO>() {

                    @Override
                    public List<GenericDTO> extract(
                            final int resultSetindex, final ResultSet rs)
                            throws SQLException {
                        while (rs.next()) {
                            result.add(rs.getString(1));
                        }

                        return Arrays
                                .asList(new GenericDTO[] { new ABCDTO() });
                    }
                }, param5, param6);

1 个答案:

答案 0 :(得分:1)

你可以使用Mockito答案(我还没有测试过这段代码):

ProxyClass mock = mock(ProxyClass.class);

when(mock.callStoredProcedure(any(), any(), any(), any(), any(), any(), any())
    .thenAnswer(new Answer<Void>() {
         public Void answer(InvocationOnMock invocation) {
             Object[] args = invocation.getArguments();
             IProxyExtractor<GenericDTO> proxyExtr = (IProxyExtractor<GenericDTO>) args[4];

             // Call the IProxyExtractor with a dummy ResultSet
             ResultSet rs = // mock ResultSet or extend it and populate it with custom data.
             GenericDTO[] dto1 = proxyExtr.extract(0, rs);
             GenericDTO[] dto2 = proxyExtr.extract(1, rs);


             return null;
         }
    });

请参阅:


如果您正在为测试实施ProxyClass,那么这样的事情应该有效:

public class TestProxyClass extends ProxyClass {

    public void callStoredProcedure(param1, 
                                    param2, 
                                    param3, 
                                    param4, 
                                    IProxyExtractor<GenericDTO> extr, 
                                    param5,
                                    param6) {

        // do something else..

        ResultSet rs = // mock ResultSet or extend it and populate it with custom data.

        // Call the IProxyExtractor with a dummy ResultSet
        GenericDTO[] dto1 = proxyExtr.extract(0, rs);
        GenericDTO[] dto2 = proxyExtr.extract(1, rs);

        // do something else..
    }

}

话虽如此,看看你的代码是否可以改进,以便IProxyExtractor实现返回一个列表而不是直接修改内部变量。您还可以使用某种收集器(受Java 8流启发),它可以作为方法参数传递给IProxyExtractor#extract