java静态方法返回对象吗_java – PowerMockito模拟单静态方法和返回对象

你想做的是1的一部分和所有2的组合。

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

但是mockStatic的2参数重载你使用Mockito / PowerMock应该做的默认策略,当你调用一个方法,你没有显式stub在模拟实例。

Creates class mock with a specified strategy for its answers to

interactions. It’s quite advanced feature and typically you don’t need

it to write decent tests. However it can be helpful when working with

legacy systems. It is the default answer so it will be used only when

you don’t stub the method call.

默认的默认存根策略是为对象,数值和布尔值方法返回null,0或false。通过使用2-arg重载,你说“不,不,不,默认情况下使用这个答案子类’answer方法来获得一个默认值,它返回一个Long,所以如果你有静态方法返回的东西不兼容长,有一个问题。

相反,使用mockStatic的1-arg版本启用静态方法的存根,然后使用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());

}

}

字符串值静态方法被存根以返回“Hello!”,而int值的静态方法使用默认的存根,返回0。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值