user5155835
user5155835

Reputation: 4742

JUnit How to Mock with varying values of parameter object?

Following is my test code using JUnit Mockito:

@Before
public void preSetup() throws Exception {   
    AuditTrail auditTrail = new AuditTrail();
    auditTrail.setEventType(1);
    auditTrail.setEventDetail("play");
    auditTrail.setEventDate(new Date());

    Mockito.doReturn(auditTrail).when(auditService).addAuditTrail(auditTrail);
}

@Test
public void testaddPlayAuditRecord() {

    boolean value = auditService.addPlayAuditRecord();
    assertEquals(true, value);
}

And my service looks like:

@Override
public boolean addPlayAuditRecord() {
    return addAuditRecord(1,"play");
}

@Override
public boolean addDeleteAuditRecord() {
    return addAuditRecord(2,"delete");
}

@Override
public boolean addSearchAuditRecord() {
    return addAuditRecord(3,"search");
}


private boolean addAuditRecord(String eventType, String eventDetail) {
    AuditTrail auditTrail = new AuditTrail();
    auditTrail.setEventType(eventType);
    auditTrail.setEventDetail(eventDetail);
    auditTrail.setEventDate(new Date());

    AuditTrail obj = auditService.addAuditTrail(auditTrail);
}

auditService.addAuditTrail(auditTrail) makes a database call which I want to mock and return a object with values of my choice.

But this auditTrail object is built by values which are dependent on which method is calling it. They vary depending on which method is calling the addAuditRecord method. Also, we're using new Date() to get the current date object. So the date I'll be using in test will be different than what I'll use in addAuditRecord since the date is current date.

So in my test file, how do I mock this addAuditTrail method? Can such mocking be done in @Before method? The auditTrail object passed here should match the object which is actually constructed in the addAuditRecord method.

How do I do this?

Upvotes: 1

Views: 167

Answers (1)

Lorelorelore
Lorelorelore

Reputation: 3393

Have you tried this?

Mockito.doReturn(auditTrail).when(auditService)
                   .addAuditTrail(ArgumentMatchers.any(AuditTrail.class));

In this way you run this rule everytime you pass an AuditTrail object, regardless his internal values.

For your Mockito version just use:

Mockito.doReturn(auditTrail).when(auditService)
                   .addAuditTrail(Matchers.any(AuditTrail.class));

Upvotes: 1

Related Questions