Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why just one test worked when using mockStatic in method modified by @BeforeClass? #1138

Open
luoyanzecs opened this issue Jul 28, 2022 · 0 comments

Comments

@luoyanzecs
Copy link

Why test1 logger the message, but I use mockStatic in @BeforeClass?
How to make test1's logger mock just using mockStatic.
junit:4.13
Test Class

@RunWith(PowerMockRunner.class)
@PrepareForTest({
        LoggerFactory.class
})
public class ServiceTest {

    @InjectMocks
    private ServiceB serviceB;

    @BeforeClass
    public static void setUpClass() {
        PowerMockito.mockStatic(LoggerFactory.class);
        PowerMockito.when(LoggerFactory.getLogger(Mockito.any(Class.class)))
                .thenReturn(PowerMockito.mock(Logger.class));
    }

    @Test
    public void test() {
        String s = serviceB.fun1();
    }

    @Test
    public void test1() {
        String s = serviceB.fun1();
    }
}

ServiceB

@Service
public class ServiceB {

    private final Logger logger = LoggerFactory.getLogger(ServiceB.class);

    @Autowired
    private ServiceA serviceA;

    public String fun1() {
        logger.info("------serviceB--log------");
        return "Hello";
    }
}

console log

23:07:53.213 [main] INFO com.example.surefiletest.service.ServiceB - ------serviceB--log------

Process finished with exit code 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant