Powermock构造函数mock对实例化的对象没有影响


    Class  A{
    B objB = new B();
    objB.someBMethod();
    }
    Class B{
    public void someBMethof(){
    C objC = new C();
    }
    }
    class C{
    int a=1;
    public C(){}
    public C(int v){
    a=v;
    }
    }
@RunWith( PoswerMockRunner.class )
@PrepareForTest({ A.class, B.class, C.class})
Class TestApp{
    @Mock
    C mockC;
    PowerMockito.whenNew( C.class ).withNoArguments().thenReturn(mockC);
}

上面的代码捕获了我要做的事情。但是whenNew()似乎没有工作,当我尝试调试创建的C对象不是mock。不知道发生了什么。如果能给点指点,我将不胜感激。由于

您提供了一些代码,所以谢谢。但是下次,考虑发布一个sscce(正确的(可编译的)示例)。

我试过(并修复你的代码),它工作。这是我对你的代码的版本:

public class A {
    public int someAMethod() {
        B objB = new B();
        return objB.someBMethod();
    }
}
public class B {
    public int someBMethod() {
        C objC = new C();
        return objC.getA();
    }
}

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ A.class, B.class, C.class })
public class TestApp {
    @Mock
    C mockC;
    @Test
    public void shoudlReturnTheCValue() throws Exception {
        when(mockC.getA()).thenReturn(666);
        PowerMockito.whenNew(C.class).withNoArguments().thenReturn(mockC);
        assertEquals(666, new A().someAMethod());
    }
}

我已经配置了一个maven项目,包含以下依赖项:

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.9.5</version>
    <scope>test</scope>
</dependency>

相关内容

  • 没有找到相关文章

最新更新