Uncategorized

Unit Testing OnClickListener with Mockito

Testing_danger_sign_290x249

 

 

 

 

It’s quite often we need to ensure our behavior for the onClickListener()s, here’s a tiny trick to do unit tests on these listeners.

Lets start by defining how we want the test to look like:

Let’s assume a Manager class is going to be the heavy lifting place where we will be setting up the onClickListener(). And we want the click event to do one simple thing, change a boolean flag from False to True, indicating the click event actually happened.

With that in place, we can start setting up our Manager class. Since we need to access the listener in the unit test class, we need to set it as a variable and allow access. It might be tempted to set up onClickListener() with the following:

public View.OnClickListener onClickListener = new View.OnClickListener(){ ... }

However, setting up this way will have one major pitfall, other variables in the class might not been initialized yet! When the clicked event eventually happened, you might be getting a NullPointerException or some random behavior! To deal with this issue, we need lazy instantiation to delay the loading of onClickListener() when the manager class get loaded.

Here, we defined that in order to setup the onClickListener(), the setUp() method must be called. And in the setUp() method, we initialize all variables that will be needed by the click event. And now the testing can begin!

Tags: ,

Discussion

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s