wujun / powermock

Automatically exported from code.google.com/p/powermock
Apache License 2.0
0 stars 0 forks source link

SuppressStaticInitializationFor issue with static Logger #479

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Create a HelloWorld class:
(You'll need SLF4J and a Logging implementation on your classpath)

package com.example.helloworld;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {

    private static final Logger LOG = LoggerFactory.getLogger(HelloWorld.class);

    private String message;

    static {
        LOG.debug("This is the static initialization block speaking");
    }

    public HelloWorld() {
        LOG.debug("I'm running the constructor now");
        initializeHelloWorld();
    }

    private void initializeHelloWorld() {
        setMessage("Hello world!");
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void sayHello() {
        LOG.error(getMessage());
    }

}

2. Create a HelloWorldTest class:
(You'll need JUnit and Powermock on your classpath)

package com.example.helloworld;

import org.junit.Assert;
import org.junit.Test;

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("com.jnj.gtsc.portal.HelloWorld")
public class HelloWorldTest {

    @Test
    public void testSayHello() {
        HelloWorld helloWorld = new HelloWorld();
        Assert.assertEquals("Hello world!", helloWorld.getMessage());
        helloWorld.sayHello();
    }

}

3. You'll see that the test fails on a NullPointerException at:

public class HelloWorld {

    public HelloWorld() {
        LOG.debug("I'm running the constructor now");
        ...
    }

}

What is the expected output? What do you see instead?
- I expect only the static initialization block of the HelloWorld class to  be 
suppressed. Not also the private static final Logger field. Is this intentional 
behavior or a bug?

What version of the product are you using? On what operating system?
- I use powermock 1.5.2 on a Windows 7 operating system.

Please provide any additional information below.
- /

Original issue reported on code.google.com by steve.sc...@gmail.com on 24 Jan 2014 at 10:15

GoogleCodeExporter commented 9 years ago
This is intended behavior since static fields are initialized during static 
initialization in Java.

Original comment by johan.ha...@gmail.com on 28 Jan 2014 at 8:52