I am a Java beginner.
As you can see in the source code below, when I searched the sample code of URL class Mock on the net, There are cases where there is no reflect and cases where there is reflect. How is the behavior different in each case?
What does a block-like description like {String.class} mean?
URL mockedURL = PowerMockito.mock(URL);
PowerMockito.when(mockedURL.openConnection()).thenReturn(mockedConnection);
// not reflect case
PowerMockito.whenNew(URL.class).withArguments(Mockito.anyString()).thenReturn(mockedURL);
// reflect case
PowerMockito.whenNew(URL.class.getConstructor(new Class<?>[]{String.class})).withArguments(Mockito.anyString()).thenReturn(mockedURL);
PowerMockito.when(mockedURL.openConnection()).thenReturn(mockedConnection);
This defines that when the openConnection()
method is called on the mockedURL
object, the value mockedConnection
is returned instead (and not the real code is called). This syntax/approach is defined/used in the "Mockito" library as well.
PowerMockito.whenNew(URL.class).withArguments(Mockito.anyString())
This will be used when you create the URL
object with a string as an argument. Using PowerMockito.whenNew()
with a class
argument allows you to use withAnyArguments()
to mock any constructor of that class, not just a specific one.
PowerMockito.whenNew(URL.class.getConstructor(new Class<?>[]{String.class}))
This is used to select the specific constructor. In this case it's the one with the String
argument. So when you write new URL("some string")
, this mock is used.
new Class<?>[]{String.class}
This is just an array with values declaration like any other. It's like writing
new int[] {4, 6, 10}
Only that the type is Class<?>
and the values are one String.class
object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.