In today’s section, we’ll see how to extend even inaccessible class and write test against that. But, before that let us assume that, you have following class
Here, It’s quite easy to write test for getFirstValue() as shown below in the snippet.
And, this will pass. Similarly, we can write test for other next one as well and that will also pass.
But, for the third one, which is private, we need to make use reflection as shown below.
Here, using reflection, I got the access of that private method and then created instance of that and hence tested the same. However, let us suppose, you would like to extend this class and make more reusable. In real time project scenario, your extension could be more meaningful. But, here for demo purpose, I am just extending the class to modify the output.
In order to test the same, I can go ahead and write the test case as shown below.
Very powerful and easy to use right!!!
Similarly, we can go ahead and extend second class as shown below.
And, again test for the same will look like
However, if we try to access the third class as shown below, it won’t be accessible, since it’s private.
Here, to rescue us again, reflection will come into picture. Below, is the snippet for the same.
Similarly, we can write test for the same as shown below.
Now, let us go ahead and add one abstract class on the top of this and extend the same. Below is the snippet in finished form.
And, its extension will look like
And, its finished Tests will look like
Makes sense right. Therefore, when you run all the tests, it will flag tests as green as shown below in the screeshot.
There are many other tests other than these, thats why I have not highlighted the same. Thanks for joining me.
2,042 total views, 1 views today