简体   繁体   English

Powermock构造函数模拟对实例化对象没有影响

[英]Powermock constructor mocking has no effect on the instantiated object

    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);

}

The above code captures what im trying to do. 上面的代码捕获了我正在尝试做的事情。 But the whenNew() does not seem to be working and when i try debuggin the C object created is not the mock. 但是whenNew()似乎不起作用,当我尝试调试时,创建的C对象不是模拟对象。 Dont know whats happening. 不知道发生了什么。 Some pointers would be much appreciated. 一些指针将不胜感激。 thanks 谢谢

You provides some code, so thanks. 您提供了一些代码,所以谢谢。 But the next time, consider to post an sscce (Correct ( Compilable ) example). 但是下一次,请考虑发布一个sscce(正确的( Compilable )示例)。

I tried (and fix your code) and it works. 我试过了(并修复了您的代码),它可以工作。 This is my version of your code : 这是我的代码版本:

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());
    }
}

I have configured a maven project with the following dependencies : 我已经配置了具有以下依赖项的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM