Skip to content

Verifying passed arguments partially

Recently, I was working on a project and I missed a case in unit tests. I didn’t want to verify each argument but rather wanted to check if an object has a certain attribute set. In the older versions of mockito, this wasn’t doable. Since mockito 2.1, you can now do argument verification through argThat. Let’s see an example of this in action.

@Test
public void testWritesWithAttributes(){
  final String myExpectedId = "expected-id"
  final Timestamp myExpectedTimestamp = Timestamp.from(Instant.now())
  final MockData mockData = new MockData();
  mockData.setId(myExpectedId);
  mockData.setEvent(MyEvent.builder().timestamp(myExpectedTimestamp).build());
    
  myMockService.saveMyData(mockData);

  verify(myDao).writeSomeData(
      argThat(id -> id.equals(myExpectedId)), anyLong(), 
      argThat(event ->  event.getTimestamp().equals(myExpectedTimestamp)));
} 

As you can see, I’m only looking for the attributes I’m interested in. I can skip the others and verify the attributes I should.

Stay updated!

Receive insights on tech, leadership, and growth.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.