Leonel
Leonel

Reputation: 29189

How to test that a method was called with the correct parameter?

My app has two classes, FireWatcher and AlarmBell. When a fire starts, the watcher should ring the bell, with a level. For small fires, ring the bell with a small alarm level, for big fires, ring the bell like crazy.

class FireWatcher {
  AlarmBell bell;
  void onFire(int fireLevel) { bell.ring(2 * fireLevel); }
}

class AlarmBell {
  void ring(int alarmLevel) { ... }
}

I want to test FireWatcher to make sure it calls method ring with the correct level. How can I do that with Mockito ?

I'd like something similar to the following, but cannot find anything in the documentation.

when(fireWatcher.onFire(1)).expect(mockAlarmBell.ring(2));

Upvotes: 0

Views: 150

Answers (1)

Garrett Hall
Garrett Hall

Reputation: 30022

You need to pass in a mocked AlarmBell.

Example:

@Test
public void watcherShouldRingTheAlarmBellWhenOnFire() {
   AlarmBell alarm = mock(AlarmBell.class);
   FireWatcher watcher = new FireWatcher(alarm);

   watcher.onFire(1);

   verify(alarm).ring(2);
}

Upvotes: 2

Related Questions