Work-hard Verifying or Work-smart Mocking

Testing is hard work, let’s make it easier

Gerald Nguyen
3 min readJan 4, 2023

--

Photo by Tim Gouw on Unsplash

Let’s test this service

@Service
public class SampleService {
private final SampleRepository sampleRepository;

public SampleService(SampleRepository sampleRepository) {
this.sampleRepository = sampleRepository;
}

public SampleEntity createSampleEntity() {
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setName("sample");

return sampleRepository.save(sampleEntity);
}
}

If we want to test the method createSampleEntity from SampleService, there are 3 things we want to verify:

  • #1 — sampleRepository.save is called,
  • #2 — with the right sampleEntity,
  • and #3 — the resulting entity is returned

Work hard Verifying

A typical unit test contains 3 stages: Arrange, Act, and Assert (or AAA)

Arrange is where we set up the test data and mock the test’s external dependencies. In the below example, we need to mock the method sampleRepository.save to return an expected entity.

Act is where we invoke the to-be-tested method with the right arguments. If the method returns something, we capture the returning value too…

--

--

Gerald Nguyen

Engineering Lead. I write about software development, and sometimes writing itself. Mostly original. https://bit.ly/geraldnguyen