pierrotlefou
pierrotlefou

Reputation: 40721

UnitTest: how to test if an Listener's update has been called

What is the simplest way to make sure the listener's update has even been called ?

Update: I am testing the Listener (not the Subject) and once update is called, the test pass.

     d.addServiceComponentChangeListener(new ServiceComponentChangeListener() {

        //In the Unittest, I want to make sure this has been called
        public void notifyChange(ServiceComponentChangeEvent event) {
            System.out.println("@notifyChange");

        }
    });

Upvotes: 2

Views: 1418

Answers (3)

D-Bar
D-Bar

Reputation: 185

I would test it by replace the call System.out or whatever that section should really do with an interface that be later mocked and use behavior verification to make sure it was called. So...

public class d 
    {
        private MessageDisplayer m_UserDisplay;

        public d()
        {
          m_UserDisplay = new DisplaySystemOut()
        }

        public d(MessageDisplayer AllowsSensing)
        {
          m_UserDisplay = AllowsSensing;
        }

    //blah blah blah....

              d.addServiceComponentChangeListener(new ServiceComponentChangeListener() 
            {
            public void notifyChange(ServiceComponentChangeEvent event) {
                m_UserDisplay.DisplayMessage("@notifyChange");

            }
        });

    } 

Now you can mock MessageDisplayer in your test and make sure it is called and that the parameter was equal to "@notifyChange"

Upvotes: 0

dj_segfault
dj_segfault

Reputation: 12429

Even if the listener does not implement an interface, you can still create a mock for it using something like Mockito. Using runtime code insertion, inspection of the class to be mocked, and purple pixie dust, it can impersonate other classes. At my company most unit tests use either Mockito (the newer ones) or EasyMock (the older ones) so we're sure we're testing JUST the one class.

I question your statement "Update: I am testing the Listener (not the Subject)", though. If your test is verifying the listener gets called, you're testing the thing that's supposed to call the listener, not listener itself. So which is it?

Upvotes: 2

Zoidberg
Zoidberg

Reputation: 10323

If the listener implements the interface you can make a mock class that implements the listener. Then you can design this mock to fit your testing. If it does not implement an interface, as long as the listeners class is not final, you could extend it.

Upvotes: 0

Related Questions