cape
cape

Reputation: 434

Test void method behavior junit and mockito

Given this service I'd like to test that the role property of stuff object is properly set:

public void saveAStuffForAnEvent(Event whatever) {
    if (whatever == null){
        Stuff stuff = StuffBuilder().role(StuffRoles.DEFAULT).build();
        stuffRepository.save(stuff);
    } else {
        Stuff stuff = StuffBuilder().role(StuffRoles.OTHER).build();
        stuffRepository.save(stuff);
    }
}

How can I test that stuff object is properly created with the DEFAULT role?

Upvotes: 0

Views: 63

Answers (1)

Konrad Początek
Konrad Początek

Reputation: 354

Use captor.

In your test create field with @Captor annotation like:

@Mock
private StuffRepository stuffRepository;

@Captor
private ArgumentCaptor<Stuff> stuffCaptor;

Then in test after:

// when
subject.saveAStuffForAnEvent(event);
// then
verify(stuffRepository).save(stuffCaptor.capture());
assertThat(stuffCaptor.getValue().getRole()).isEqualTo(StuffRoles.DEFAULT);

Or if it's integration test then:

// when
subject.saveAStuffForAnEvent(event);
//then
assertThat(subject.findAll().get(0).getRole()).isEqualTo(StuffRoles.DEFAULT);

Upvotes: 4

Related Questions