tiebin-zhang / powermock

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

When mocking in the @BeforeClass method, the first JUnit test does not reset the initialized mocks before running itself #378

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
- create static mocks in @BeforeClass method
- create same static mocks in @Before method
- have two @Test methods

What is the expected output? What do you see instead?
I'm not sure, I think this is abnormal the mocks are not reset before launching 
the first @Test the method, despite they mocks are reset before running the 
second @Test method

What version of the product are you using? On what operating system?
version of the product: 
- powermock-mockito-1.4.9-full.jar
- mockito-all-1.8.5.jar
- junit-4.8.2.jar

Please provide any additional information below.

In the following test case the first @Test method fails because the         
assertThat(StaticClass.getValue(INPUT_1), is(INPUT_1)); in @Before method 
returns the mocked value:

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ MockIntoSetUpBeforeClassTest.StaticClass.class })
public class MockIntoSetUpBeforeClassTest {

    private static final String INPUT_1 = "INPUT 1";

    private static final String MOCKED_VALUE = "MOCKED VALUE";

    @BeforeClass
    public static void setUpBeforeClass() throws Throwable {
        prepareMocks();
        assertBase();
    }

    private static void prepareMocks() {
        // By default the method StaticCall.getValue(String) returns the value provided as parameter
        assertThat(StaticClass.getValue(INPUT_1), is(INPUT_1));

        mockStatic(StaticClass.class);

        when(StaticClass.getValue(INPUT_1)).thenReturn(MOCKED_VALUE);
    }

    @Before
    public void setUp() throws Exception {
        prepareMocks();
    }

    @Test
    public void test1() {
        assertBase();
    }

    @Test
    public void test2() {
        assertBase();
    }

    public static void assertBase() {
        assertThat(StaticClass.getValue(INPUT_1), is(MOCKED_VALUE));
    }

    public static class StaticClass {

        public static String getValue(String inputValue) {
            return inputValue;
        }

    }

}

Original issue reported on code.google.com by axelm79 on 13 Mar 2012 at 3:36