JUnit + jMock and log4j

I set the task to make JUnit + JMock in a program created by another programmer. In most classes, this static field logger, i.e.:

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

I create an instance of SomeClass by creating it inside my setUp() method. When I run my jUnit class, I get the following error message:

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

I tried to configure log4j manually by calling DOMConfigurator.configure("log4j.xml"); inside the setUp() method, but I still get the same error message above.

The question arises:

  • How can I run my unit test + mocking in a class that calls another class that uses LogFactory.getLog
  • Should I configure log4j inside my installation method so that mocking and unit test run without exception?
  • How should I do it.
+4
source share
2 answers

There are actually two types of problems that I have that I considered to be one log4j problem in jUnit. You can really continue working with jUnit + jMock, even if log4j is not configured properly, it will throw an exception but it will not stop jUnit from executing.

The problem I have is:
1. FileNotFoundException with the message "setFile (null, true) call failed"
2. An error occurred while calling jMock.

I solved number 1 (although I could still continue unit testing even with the exception of log4j) by setting the argument VM -Dlog4j.configuration=file:/C:/log4j/log4j.xml . I was getting an exception because it used log4j.xml inside the compiled directory (the default output folder for compiled Java classes). This log4j has this parameter <param name="File" value="${error.file}"/> . Therefore, log4j looks for a log file that has the file name $ {error.file} (which does not exist). Like what I said above, I solved this by putting the VM argument above.

Lesson learned: if you get a FileNotFoundException in log4j execution, try putting -Dlog4j.debug as a VM argument to see where log4j pulls out the configuration file.

I solve number 2 by completing the entire expected object inside the method that I am testing. Although the jMock message is fuzzy ambiguous.

Lesson learned: Unexpected access usually means that you skip objects or layouts in the test method that are used in the method that you test on the module. It also means that you did not set the expectations of the object that it is trying to call.

+1
source

You have two options ...

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

+4
source

Source: https://habr.com/ru/post/1392524/


All Articles