File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to mock final class in unittest

 
jim xu
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rodrigo Lopes
Ranch Hand
Posts: 119
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that JMockit can help you.
You can write your MockLog class and use


[ April 18, 2008: Message edited by: R Lopes ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic