jUnit + jMock and log4j

4k Views Asked by At

I've given a task to do a JUnit + JMock on a program created by other programmer. Most of the class has this static field logger, i.e.:

static Log logger = LogFactory.getLog(SomeClass.class.getName());

I am creating an instance of SomeClass by instantiating it inside my setUp() method. When I run my jUnit class I am getting this error message:

log4j:ERROR setFile(null,true) call failed.
java.io.FileNotFoundException:  (No such file or directory)

I tried to do the the manual log4j configuration by calling DOMConfigurator.configure("log4j.xml"); inside the setUp() method but I'm still getting the same error message above.

The question is:

  • How can I run my unit test + mocking in a class which calls other class that uses LogFactory.getLog
  • Should I configure log4j inside my setup method so that the mocking and unit test runs without an exception?
  • How should I do it.
2

There are 2 best solutions below

0
On BEST ANSWER

Actually there are two types of problem that I have which I thought to be one, a log4j problem in jUnit. You can actually continue with the jUnit + jMock even if log4j is not configured properly it will throw an exception but won't stop jUnit execution.

The problem that I have are:
1. FileNotFoundException exception with message "setFile(null, true) call failed"
2. jMock unexpected invocation error

I solved number 1 (even though I could still continue unit testing even with log4j exception) by putting a VM argument -Dlog4j.configuration=file:/C:/log4j/log4j.xml. I was getting an exception because it was using the log4j.xml inside the compiled directory (default output folder for compiled java classes). That log4j has this parameter <param name="File" value="${error.file}"/>. So log4j is looking for a log file that has a file name ${error.file} (which doesn't exist). Like what I said above I solved it by putting a VM argument above.

Lesson learned: If you are getting FileNotFoundException in log4j execution try to put -Dlog4j.debug as a VM argument to see where log4j is pulling the config file.

I solve number 2 by completing all the expected object inside the method that I am testing. Though jMock message is kinda ambiguous.

Lesson learned: Unexpected invocation usually means you are missing an objects or mock-objects in your test-method that are being used in the method that you are unit testing. It also means you haven't set an expectations on the object that it is trying to invoke

1
On

You have two options...

In Maven projects, the second option is easy since you simply need to create a log4j.properties in your test/resources folder.