I have a class which takes a message with payload String. The payload is then split and used to create an Entity which is passed to DAOInterface to persist.

How can you test the call daoInterface.insert(entity) has been made?

To Mock the DAOInterface and then verify the call to DAO requires the entity in the test class which you dont have i.e.


Is this bad design i.e. creating the entity at this stage? Should the Sting[] split be passed to the DAOImplementaion and initialized there. Example problem,

public class ServiceClass {

    private DAOInterface daoInterface;

    public void serviceMessage(Message<String> message) {

        MessageHeaders mh = new MessageHeaders(message.getHeaders());       
        String[] split = ((String) mh.get("payload")).split("_");

        code omitted

        String type = mh.get("WhatType");

        Entity entity = new Entity(split[0], split[1], split[2]);

        if (type.equals("one"))
            daoInterface.insert(entity); //How to verify this call?
            if (type.equals("two"))
                doaInterface.modify(entity); //How to verify this call?

1 Answer 1


Yes, you can verify daoInterface.insert is called with verify(daoInterface).insert(anyObject());, but you have to mock DaoInterface first with DaoInterface db = mock(DaoInterface.class);. verify(daoInterface).insert(entity); will fail all the time because entity object from verify's argument and entity inside serviceMessage() are different instance. Instead, you can implement an entity matcher to make sure entity contents are match,

public class EntityMatcher extends ArgumentMatcher<Entity> {
    private Entity mEntity;

    public EntityMatcher(Entity entity) {
        mEntity = entity;

    public boolean matches(Object argument) {
        Entity entity = (Entity)argument;

        if (mEntity.equals(entity)) {
            return true;

        return true;


A working test example can be,

public void test() {
    DaoInterface db = mock(DaoInterface.class);

    ServiceClass service = new ServiceClass(db);

    verify(db).insert(argThat(new EntityMatcher(
        new Entity("a", "b", "c")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.