如何使用JMockit模拟DAO层?

时间:2016-02-15 16:30:54

标签: java unit-testing junit mocking jmockit

我正在尝试模拟一个看起来像这样的DAO层接口...

      public interface DummyDAO{

     public List<VO> getSearchCriteria(String Id, Integer version) throws Exception;

      }

在实现部分中,我运行一个查询,它根据该查询获取一个Value对象列表。如何模拟来自数据库的VO列表。有一个简单的方法吗?我试图鼓励我的团队使用Jmockit,但我仍然是这个嘲弄工具的新手。如果您需要更多信息,请告诉我。

由于

2 个答案:

答案 0 :(得分:2)

这里的答案部分取决于CUT(被测代码)如何使用List<VO>。例如,如果您的代码是仅作为代理的RESTful服务并将此List<VO>返回给用户,而不检查内容或任何内容,那么这就足够了:

@Tested CUT cut;
@Injectable DummyDAO dao;
@Injectable List<VO> res;

@Test
public void testSomething() throws Exception {
    new Expectations() {{
        dao.getSearchCriteria(anyString, anyInt); result = res; 
    }};
    List<VO> output = cut.methodBeingTested();
    // assertions go here, like that output and res are the same
    // you can also put Verifications here
}

如果您希望对VO进行分析,那么事情会变得更加复杂,例如:

@Tested CUT cut;
@Injectable DummyDAO dao;
@Mocked VO vo;

@Test
public void testSomething() throws Exception {
    final List<VO> res = new ArrayList<VO>();
    Collections.addAll(res, vo, vo, vo, vo);
    new Expectations() {{
        dao.getSearchCriteria(anyString, anyInt); result = res;
    }};

    new Expectations(4) {{
        vo.getFoo(); returns(5, 47, 13, -7);
    }};

    cut.methodBeingTested();
    // assertions go here, like that you handled the negative number properly
    // you can also put Verifications here
}

请注意,我没有嘲笑List - 如果你正在进行更复杂的操作,最好坚持使用真实的List,而不必嘲笑它的所有操作。我嘲笑一个单独的VO并将其多次添加到列表中 - 这是可以的,因为每次检查它时它会采取不同的行为,因此看起来是不同的VO

考试,因为它发生了4次,我搬到了另一个Expectations区块,因为你期望它发生4次。我只是这样做是为了炫耀期望块,因为在这种情况下,通过在原始块中使用vo.getFoobar(); times=4; returns(5, 47, 13, -7);可以很容易地实现...或者,第二个块可能看起来像

    new StrictExpectations(4) {{
        vo.getFoo(); returns(5, 47, 13, -7);
        vo.getBar(); returns("foo", "bar", "baz", "quux");
    }};

在这种情况下,times字段不起作用,您必须将其放在一个单独的块中 - 此块表示它希望getFoo()和{{1} }调用,交替,恰好4次 - 如果你想在每次迭代列表并查看这两个属性时想要做的话。

我希望我能给你一些思考的食物;在不了解您的具体用例的情况下,我自己可以更具体。

答案 1 :(得分:0)

一种简单的方法是使用Mockito.spy()。间谍方法创建实例的代理,使您有机会模拟一种方法的行为。

您可以创建一个在调用dao方法时返回的列表。

示例:

yourDao = spy(new YourDaoImplementation())
        doReturn(yourExampleList).when(yourDao).getSearchCriteria(any(String.class), any(Integer.class));

如果你真的想测试你的dao,你可以使用轻量级数据库作为HSQLDB

相关问题