相关疑难解决方法(0)

使用PowerMock模拟私有方法,但仍会调用基础方法

我试图嘲笑模拟一个正在进行JNDI调用的私有方法.当从单元测试调用该方法时,它会抛出异常^.我想嘲笑这种方法用于测试目的.我使用了来自另一个问题答案示例代码,并且在测试通过时,似乎仍然调用了基础方法.我System.err.println()doTheGamble()方法中插入了一个,然后打印到我的控制台.

有趣的是,如果我将第一个注释掉assertThat,测试就会通过.?:(

那么,我如何模拟私有方法,以便它不被调用?

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

import java.util.Random;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class PowerMock_Test {

    static boolean gambleCalled = false; 

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());

        when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
                .withArguments(anyString(), anyInt())
                .thenReturn(true);

/* 1 */ assertThat( …
Run Code Online (Sandbox Code Playgroud)

java junit mockito powermock

27
推荐指数
1
解决办法
6万
查看次数

标签 统计

java ×1

junit ×1

mockito ×1

powermock ×1