Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java类中模拟特定的静态方法?_Java_Junit_Mockito_Powermockito - Fatal编程技术网

如何在java类中模拟特定的静态方法?

如何在java类中模拟特定的静态方法?,java,junit,mockito,powermockito,Java,Junit,Mockito,Powermockito,在我的测试类中有许多静态方法,但我只想模拟测试类的一个特定方法 是否有任何方法可以让我模拟只有特定的方法,而静态方法的其余部分行为正常 以及如何为特定值使用存根方法 假设这是我的方法 PowerMockito.stub(PowerMockito.method(ServiceUtils.class,“getBundle”,String.class)).toReturn(bundle) 我希望getBundle方法对于传递的不同参数有不同的行为 字符串可以是abc或def,所以对于每个字符串,get

在我的测试类中有许多静态方法,但我只想模拟测试类的一个特定方法

是否有任何方法可以让我模拟只有特定的方法,而静态方法的其余部分行为正常

以及如何为特定值使用存根方法

假设这是我的方法 PowerMockito.stub(PowerMockito.method(ServiceUtils.class,“getBundle”,String.class)).toReturn(bundle)

我希望getBundle方法对于传递的不同参数有不同的行为 字符串可以是abc或def,所以对于每个字符串,getbundle方法的行为应该不同


我只想知道,有没有任何方法可以代替PowerMockito.method中的String.class来传递像“abc”这样的值。

您可以这样做(如果您使用mokito)


您可以创建真实对象的间谍。当您使用spy时,将调用真正的方法(除非方法被存根)

下面是官方文档中的一个示例

List list = new LinkedList();
List spy = spy(list);

//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);

//using the spy calls *real* methods
spy.add("one");
spy.add("two");

//prints "one" - the first element of a list
System.out.println(spy.get(0));

//size() method was stubbed - 100 is printed
System.out.println(spy.size());

//optionally, you can verify
verify(spy).add("one");
verify(spy).add("two");
List list = new LinkedList();
List spy = spy(list);

//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);

//using the spy calls *real* methods
spy.add("one");
spy.add("two");

//prints "one" - the first element of a list
System.out.println(spy.get(0));

//size() method was stubbed - 100 is printed
System.out.println(spy.size());

//optionally, you can verify
verify(spy).add("one");
verify(spy).add("two");