简体   繁体   中英

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));

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM