【问题标题】:Mocking final class with parameterized constructor使用参数化构造函数模拟最终类
【发布时间】:2016-11-02 05:02:44
【问题描述】:

我有如下最后一堂课

public  class firstclass{

   private String firstmethod(){

       return new secondclass("params").somemethod();

}

}


public final class secondclass{

   secondclass(String params){

        //some code

}

public String somemethod(){

         // some code 
        return somevariable";
}
}

我必须在这里测试头等舱,所以我将其模拟如下

secondclass classMock = PowerMockito.mock(secondclass .class);
        PowerMockito.whenNew(secondclass .class).withAnyArguments().thenReturn(classMock);
Mockito.doReturn("test").when(classMock).somemethod();

但这并没有像我预期的那样嘲笑任何人可以帮助我吗?

【问题讨论】:

  • 你为什么要模拟最后一堂课?如果它是最终的,则不应该以这种方式使用。
  • 我必须测试 firstclass firstmethod。因为有一个返回 somevariable 的第二类 somemethod 的调用,所以我嘲笑它返回测试值
  • 那么你应该设计第一个类来接受一个接口。如果您的第一堂课正在调用最后一堂课,就是这样,您无法更改它。
  • 不,我不能更改代码。所以没有办法嘲笑吗?
  • 不,除非您更改代码,否则您无法更改它。在这种情况下,最小的可能被测单元是firstclass secondclass 作为一个联合体。

标签: java junit mockito powermockito


【解决方案1】:
  1. 方法firstclass.firstmethod() 是私有方法。所以尝试通过调用它的公共方法来测试这个方法。

  2. 您可以使用@RunWith(PowerMockRunner.class)@PrepareForTest(SecondClass.class) 注释模拟SecondClass 及其最终方法。

请看下面的工作代码:

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

@RunWith(PowerMockRunner.class)
@PrepareForTest(SecondClass.class)
public class FirstClassTest{


    @Before
    public void init() {

    }

    @After
    public void clear() {

    }

    @Test
    public void testfirstmethod() throws Exception{

        SecondClass classMock = PowerMockito.mock(SecondClass.class);
        PowerMockito.whenNew(SecondClass.class).withAnyArguments().thenReturn(classMock);
        Mockito.doReturn("test").when(classMock).somemethod();

        new FirstClass().firstmethod();
    }
}

使用的库:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2017-04-01
    • 1970-01-01
    相关资源
    最近更新 更多