Java – I can automatically execute JUnit test cases once when all logging is enabled and automatically execute after all logging is disabled

I have found a solution. Please refer to the answer below Does anyone have something more elegant?

I think this is to increase code coverage and find subtle errors@ H_ 403_ 3@

Suppose you want to test the following classes: @ h_ 403_ 3@

public class Foo {
    private final Logger logger = LoggerFactory.getLogger(Foo.class);
    public void bar() {
        String param=[..];
        if(logger.isInfoEnabled()) logger.info("A message with parameter {}",param);

        if(logger.isDebugEnabled()) {
            // some complicated preparation for the debug message
            logger.debug([the debug message]);
        }
    }
}

And the following test classes: @ h_ 403_ 3@

public class FooTest {
    @Test
    public void bar() {
        Foo foo=new Foo();
        foo.bar();
    }
}

Code coverage tools such as cobertura will correctly report that only some conditional branches are checked@ H_ 403_ 3@

Activate or deactivate the recorder information and debug@ H_ 403_ 3@

Besides looking bad on your report score, it also poses a real risk @ H_ 403_ 3@

What if the internal code (logger. Isdebuginabled()) causes some side effects? What if your code only works when debug is enabled and fails if the log level is set to info? (this actually happened in one of our projects: P) @ h_ 403_ 3@

So my conclusion is that code containing logger statements should always be tested once when all logging is enabled and @ h when all logging is disabled_ 403_ 3@

Is there any way to do such a thing with JUnit? I know how to enable or disable all logging in logback globally, so the problem is: how to perform two tests with logging enabled and disable logging once@ H_ 403_ 3@

PS: I know this question, but I don't think it's repeated I don't care much about absolute override values, but about subtle and hard to find errors that may be contained in if (logger. Isdebuginabled())@ H_ 403_ 3@

Solution

I solve this problem by implementing a base class. If such a function is required, the test class should be extended

Article writing a parameterized JUnit test contains the solution@ H_ 403_ 3@

For information about logging base classes, see logging testbase; For a simple example of using it, see logging testbaseexampletest@ H_ 403_ 3@

Each included test method is executed three times: @ h_ 403_ 3@

1. Use logback test as usual Log execution defined in XML This should help write / debug tests@ H_ 403_ 3@

2. Execute when all logging is enabled and written to the file Delete this file after testing@ H_ 403_ 3@

3. Execute when all logging is disabled@ H_ 403_ 3@

Yes, loggingtestbase requires documentation;)@ H_ 403_ 3@

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>