Take the 2-minute tour ×
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. It's 100% free, no registration required.

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.

verify(daoInterface).insert(entity);

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 {

    @AutoWire
    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?
        }
        else
        {
            if (type.equals("two"))
            {
                doaInterface.modify(entity); //How to verify this call?
            }
        }
    }
}
share|improve this question

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;
    }

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

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

        return true;
    }

}

A working test example can be,

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

    ServiceClass service = new ServiceClass(db);
    service.serviceMessage("a_b_c");

    verify(db).insert(argThat(new EntityMatcher(
        new Entity("a", "b", "c")
    )));
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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