Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Testing and the fly likes how to test System.console Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » Testing
Bookmark "how to test System.console" Watch "how to test System.console" New topic
Author

how to test System.console

Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30973
    
159

I'm writing some code that deals with System.console(). For console.reader(), it is fine as I can pass in a reader. For console.readPassword(), I'm at a loss. I had to resort to creating a mock subclass that returns a "test password.". That feels like a hack. Any better ideas? I could wrap it an interface, but that's not any better.

The problem is that Console is final, lacks an interface and lacks a constructor. And as an added bonus System.console() returns null in a JUnit test.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Tim Cooke
Bartender

Joined: Mar 28, 2008
Posts: 1174
    
  65

What a total nuisance this is! It wouldn't be so bad if Console weren't final.

Have you tried using one of the more elaborate mocking frameworks such as PowerMock for swapping out final classes? I haven't actually tried this framework for final classes but it works well enough for mocking static methods (using some Reflection Wizardry).

Alternatively you could write an adaptor for the System interaction which can be swapped out with a fake in your testing. This is basically wrapping it in an interface as you already mentioned. However, how do you then test the adaptor?

One one hand I would say that by using something like PowerMock you could achieve a technically more complete test coverage, but it does add a good degree of noise to your test cases as the API is relatively verbose. On the other hand introducing an adaptor for your System interaction is the more elegant solution, and the one most discussed in the books on Testing that I've read, but does leave you with an adaptor that still has a dependency on Console that you can't work with.

A combination of each may be the way to go. Wrap it up in an adaptor so that the rest of your system, and test, only has to deal with the dreamy adaptor interface, then use PowerMock to test the in's and out's of your interaction with System and Console while keeping the scope of those tests small within the bounds of the adaptor implementation.


Tim Driven Development
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to test System.console