简体   繁体   中英

Mocking Db in Java Unit tests

I am trying to unit test this code block in a method in my service layer. Could anyone suggest what can (/should) I test here and how to test them (esp. the insert to db part). Any pointers (/example code/doc) will be very helpful.

if (element != null) {
    id = iplDAO.loadGames(element, batchVO.getId());
    iplPartyDetailsVO = element.getParty();
    if iplPartyDetailsVO != null) {
    try {
        iplDAO.insertPartyDetails(iplPartyDetailsVO, id, batchVO.getId());
    } catch (Exception e) {

        logger.logp("className");
        String err = "blah";
        iplDAO.insertIntoError(err_t);
    }
}

I think you might be confusing the testing with the mocking, if you are trying to write tests for this service layer code then you need to decide what are your expectations, for example:

  • Load some games from a data source
  • Save something (it's not clear in your code what you are actually saving but writing some unit tests might make this more obvious).

So if these are your expectations for your code then you would need to write a test that can verify that they have been met.

This means mocking the dependency that you are calling (in your case the iplDAO object) so that each method call returns something that can be used to test your functionality - in your case these two calls:

 iplDAO.loadGames(element,batchVO.getId())

and

iplDAO.insertPartyDetails(iplPartyDetailsVO, id,batchVO.getId());

There are lots of Java mocking libraries to choose from and they are all well documented but this blog post is a good starting point.

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