Spies are used to make existing classes into Mockito classes. Say your class under test hooks into a Java listener, so you want some kind of dummy listener for it to hook into. You can't do this with Mockito (at least I can't find a way), but you can make your own:
//listener interface public interface SomethingListener { //change that sends the event public void somethingChanged(EventObject e); } //our little dummy listener provider public class DummyListenerProvider { private SwitchListener listener; //this is used by the class under test public void addSwitchListener(SwitchListener listener) { this.listener = listener; } //send event, saying the class is the source public void triggerEvent() { this.listener.somethingChanged(new EventObject(this)); } //used by the event consumer when the event occurs public void switchMeOn(boolean isTrue) { } }Cool, but you still want all the nice little trinkets that come with the Mockito objects. This is where spies come in. You just wrapper the class using spy instead of mock:
DummyListenerProvider spyListenerProvider = spy(new DummyListenerProvider()); ClassUnderTest underTest = new ClassUnderTest(spyListenerProvider); spyListenerProvider.triggerEvent(); verify(spyListenerProvider).switchMeOn(true);
No comments:
Post a Comment