PowerMockito模拟单个静态方法和返回对象

use*_*653 89 java easymock mockito powermock java-ee

我想从包含2个静态方法m1和m2的类中模拟静态方法m1.我希望方法m1返回一个对象.

我尝试了以下内容

1)

PowerMockito.mockStatic(Static.class, new Answer<Long>() {
         @Override
         public Long answer(InvocationOnMock invocation) throws Throwable {
            return 1000l;
         }
      });
Run Code Online (Sandbox Code Playgroud)

这是调用m1和m2,它们具有不同的返回类型,因此它给出了返回类型不匹配错误.

2)PowerMockito.when(Static.m1(param1, param2)).thenReturn(1000l); 但是当执行m1时不会调用它.

3)PowerMockito.mockPartial(Static.class, "m1"); 给出了mockPartial不可用的编译错误,这是我从http://code.google.com/p/powermock/wiki/MockitoUsage获得的.

Tom*_*sky 126

你想要做的是1部分和2部分的组合.

您需要使用PowerMockito.mockStatic为类的所有静态方法启用静态模拟.这意味着可以使用when-thenReturn语法对它们进行存根.

但是你正在使用的mockStatic的2参数重载提供了一个默认策略,当你调用一个你没有在mock实例上明确存根的方法时,Mockito/PowerMock应该做什么.

来自javadoc:

创建具有指定策略的类模拟,以获取其交互的答案.它是非常先进的功能,通常你不需要它来编写体面的测试.但是,在使用旧系统时它会很有用.它是默认答案,因此只有在不存根方法调用时才会使用它.

默认默认磕碰的策略是只返回NULL,0或假的对象,数量和价值布尔方法.通过使用2-arg重载,你会说"不,不,不,默认情况下使用此Answer子类'的答案方法来获取默认值.它返回一个Long,所以如果你有静态方法返回与之不兼容的东西很长,有一个问题.

相反,使用1-arg版本的mockStatic来启用静态方法的存根,然后使用when-thenReturn指定要对特定方法执行的操作.例如:

import static org.mockito.Mockito.*;

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

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}
Run Code Online (Sandbox Code Playgroud)

存根的String值静态方法返回"Hello!",而int值静态方法使用默认存根,返回0.

  • `@ PrepareForTest`注释应该是*调用*静态方法的类,而不是静态方法所在的类. (6认同)
  • @HazelTroost-不,OP是正确的。该类包含应为测试准备的静态方法。因此,@ PrepareForTest(ClassWithStatics.class)`是正确的。 (3认同)
  • 给了我一个“MissingMethodInitationException” (3认同)
  • 但是如果我需要确保使用精确的参数调用某些静态方法呢? (2认同)