PowerMock

The characteristics of

PowerMock is a more powerful framework that extends other mock frameworks such as EasyMock. PowerMock uses a custom classloader and bytecode operations to simulate static methods, constructors, final classes and methods, private methods, removal of static initializers, and more.

annotations

@runwith Annotation: powerMock

@ PrepareForTest: static

Mock: The Mock annotation creates an instance of all Mock, with all properties and methods null (0 or null).

The @spy :Spy annotation creates an instance without a Mock, and all member methods are executed as the original method logic until a Mock returns a specific value.

Note: The variables of the @spy annotation need to be initialized, otherwise an exception will be thrown when executed

@InjectMocks: The InjectMocks annotation creates an instance that can call the methods of real code, and the rest of the instances created with the @mock or @spy annotation are injected into that instance.

Captor: The Captor annotation creates a parameter catcher at the field level. But, before the test start, you must call MockitoAnnotations. OpenMocks initialized (this)

@ PowerMockIgnore annotations

To resolve a ClassLoader error after using PowerMock.

use

Final

The @runWith and @prepareForTest annotations are used when emulating final classes or final methods

@RunWith(PowerMockRunner.class)

@PrepareForTest({TargetClass.class})

Circle circle = PowerMockito.mock(Circle.class);
Copy the code

Static

You must annotate “@runwith” and “@prepareFortest”

PowerMockito.mockStatic(Class clazz);
Copy the code

Spy

Simulate partial methods of a class

We only want to emulate some of its methods, and we want the other methods to be the same, using powerMockito.spy instead of powerMockito.mock. Thus, the method set by the WHEN statement calls the mock method; Methods that are not set by the WHEN statement call the original method.

PowerMockito.spy(Class clazz);
Copy the code

A partial method that simulates an object

T PowerMockito.spy(T object);
Copy the code

When statement

When (). ThenReturn () mode

Used to simulate object methods, executing the original method and then returning the expected value, exception, reply, or calling the real method.

When (mockObject.somemethod (someArgs)).thenReturn(expectedValue); When (mockObject.somemethod (someArgs)).thenthrow (expectedThrowable); When (mockObject.somemethod (someArgs)).thenAnswer(expectedAnswer); // Expect answer powermockito.when (mockObject.somemethod (someArgs)).thenAnswer(expectedAnswer); // Call powerMockito.when (mockObject.somemethod (someArgs)).thencallRealMethod ();Copy the code

DoReturn (). When () mode

Used to simulate object methods, under a SPY instance: directly return the expected value, exception, reply, or call the real method without executing the original method.

PowerMockito.doReturn(expectedValue).when(mockObject).someMethod(someArgs);



PowerMockito.doThrow(expectedThrowable).when(mockObject).someMethod(someArgs);



PowerMockito.doAnswer(expectedAnswer).when(mockObject).someMethod(someArgs);



PowerMockito.doNothing().when(mockObject).someMethod(someArgs);



PowerMockito.doCallRealMethod().when(mockObject).someMethod(someArgs);
Copy the code

WhenNew simulation construction method

PowerMockito.whenNew(MockClass.class).withNoArguments().thenReturn(expectedObject);

PowerMockito.whenNew(MockClass.class).withArguments(someArgs).thenReturn(expectedObject);
Copy the code

Parameter matching machine

Any value

AnyInt (), mockito.anystring, mockito.any (Class clazz), etc.

The parameter match

When we use a parameter matcher, we should use the matcher for all parameters. If you want to specify a specific value for a parameter, you need to use the mockito.eq () method.

Add the matcher

Mockito’s AdditionalMatchers class provides some rarely used parameter matchers. We can compare arguments greater than (GT), less than (lt), greater than or equal to (GEQ), less than or equal to (LEQ), and so on. It can also carry out logical calculation of parameters and (and), or (OR), not, etc.

Verify the statement

Validation is the confirmation that during the simulation, the method under test has interacted with any of its dependent methods in the way expected.

Used to simulate object methods that directly return the expected value, exception, reply, or call the real method without executing the original method.

Mockito.verify(mockObject[,times(int)]).someMethod(somgArgs);
Copy the code

Validate method calls

        mockList.clear();
        Mockito.verify(mockList).clear();
Copy the code

Verify the number of method calls

Timess, atLeastOnce, atLeast, Only, atMostOnce, atMost, etc.

        mockList.clear();
        Mockito.verify(mockList, Mockito.times(1)).clear();
Copy the code

Verify the call order

InOrder inOrder = Mockito.inOrder(mockedList);
        inOrder.verify(mockedList).add(1);
        inOrder.verify(mockedList).add(2);
        inOrder.verify(mockedList).add(3);
Copy the code

Validate call parameters

ArgumentCaptor<Integer> argumentCaptor = ArgumentCaptor.forClass(Integer.class);
        Mockito.verify(mockedList, Mockito.times(3)).add(argumentCaptor.capture());
Copy the code

Make sure validation is complete

Mockito provide Mockito verifyNoMoreInteractions method, can use this method, after all the validation method to ensure that all calls are verified. If there are any unvalidated calls on the mock object, the NoInteractionsWanted exception is thrown.

Validate static methods

PowerMockito.verifyStatic(StringUtils.class);
Copy the code

Private property

ReflectionTestUtils. SetField set private property values.

 ReflectionTestUtils.setField(userService, "userLimit", expected);
Copy the code

Can use Whitebox. SetInternalState method set private properties

 Whitebox.setInternalState(userService, "userLimit", expected);
Copy the code

Private methods

It is also possible to emulate private methods through mock method stubs. However, you can only simulate the return value of the entire method, not the return value of the specified parameter.

PowerMockito.stub(PowerMockito.method(UserService.class, "isSuperUser", Long.class)).toReturn(! expected);Copy the code

test

Method method = PowerMockito.method(UserService.class, "isSuperUser", Long.class);
        Object actual = method.invoke(userService, userId);
Copy the code

validation

PowerMockito.verifyPrivate(userService).invoke("isSuperUser", userId);
Copy the code