wood burning stoves 2.0*
The moose likes Testing and the fly likes How to mock final class in unittest Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » Testing
Bookmark "How to mock final class in unittest" Watch "How to mock final class in unittest" New topic
Author

How to mock final class in unittest

jim xu
Greenhorn

Joined: Nov 18, 2007
Posts: 6
I had a hard time to figure out how to do a unittest for a method. Need some help here..



So basically, I want to unittest the fetchRows method for this class (snippet stripped off a bit in order to just show the problem). The Log class is provided by vendor's API and its a final class. I can't change it. The problem is the 'e' method requires a specific device console to establish and its a native code. In unittest environment, it just throws UnsatisfiedLinkError because there isn't such device there. I am thinking to use another mock logging class to replace the Log during runtime so that it wouldn't puke. (Like a duck typing in python) But I don't know how to do this in Java.

For example, if in python, it would be something like:

Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

You can't do duck typing in Java.

Can't you change your unit test environment so it has access to this resource? Or alternatively, can't you change your unit test to expect the UnsatifiedLinkError (if the exception is thrown) and handle it accordingly?

NB: there are logging frameworks out there that will provide an abstraction layer on top of your logging implementation. Not sure what your Log class is, but these might support it. If you changed your code to use one of these you could configure it to use differernt implemnentations depending on the environment the code is being run it. See Commons logging for example.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Rodrigo Lopes
Ranch Hand

Joined: Feb 29, 2008
Posts: 119
I believe that JMockit can help you.
You can write your MockLog class and use


[ April 18, 2008: Message edited by: R Lopes ]
 
jQuery in Action, 2nd edition
 
subject: How to mock final class in unittest