Class PowerMockito
- java.lang.Object
-
- org.powermock.api.support.membermodification.MemberMatcher
-
- org.powermock.api.support.membermodification.MemberModifier
-
- org.powermock.api.mockito.PowerMockito
-
public class PowerMockito extends MemberModifier
PowerMockito extends Mockito functionality with several new features such as mocking static and private methods and more. Use PowerMock instead of Mockito where applicable.- See Also:
Mockito
-
-
Field Summary
Fields Modifier and Type Field Description private static PowerMockitoCore
POWERMOCKITO_CORE
-
Constructor Summary
Constructors Constructor Description PowerMockito()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static PowerMockitoStubber
doAnswer(org.mockito.stubbing.Answer<?> answer)
Use doAnswer() when you want to stub a void method with genericAnswer
.static PowerMockitoStubber
doCallRealMethod()
Use doCallRealMethod() when you want to call the real implementation of a method.static PowerMockitoStubber
doNothing()
Use doNothing() for setting void methods to do nothing.static PowerMockitoStubber
doReturn(java.lang.Object toBeReturned)
Use doReturn() in those rare occasions when you cannot usewhen(Object)
.static PowerMockitoStubber
doReturn(java.lang.Object toBeReturned, java.lang.Object... othersToBeReturned)
Same asdoReturn(Object)
but sets consecutive values to be returned.static PowerMockitoStubber
doThrow(java.lang.Throwable toBeThrown)
Use doThrow() when you want to stub the void method with an exception.static <T> T
mock(java.lang.Class<T> type)
Creates a mock object that supports mocking of final and native methods.static <T> T
mock(java.lang.Class<T> classToMock, org.mockito.MockSettings mockSettings)
Creates a mock with some non-standard settings.static <T> T
mock(java.lang.Class<T> classToMock, org.mockito.stubbing.Answer defaultAnswer)
Creates mock with a specified strategy for its answers to interactions.static void
mockStatic(java.lang.Class<?> type, java.lang.Class<?>... types)
Enable static mocking for all methods of a class.static void
mockStatic(java.lang.Class<?> classToMock, org.mockito.MockSettings mockSettings)
Creates a class mock with some non-standard settings.static void
mockStatic(java.lang.Class<?> classMock, org.mockito.stubbing.Answer defaultAnswer)
Creates class mock with a specified strategy for its answers to interactions.static <T> void
spy(java.lang.Class<T> type)
Spy on classes (not "spyable" from normal Mockito).static <T> T
spy(T object)
Spy on objects that are final or otherwise not "spyable" from normal Mockito.static <T> ConstructorArgumentsVerification
verifyNew(java.lang.Class<T> mock)
Verifies certain behavior happened oncestatic <T> ConstructorArgumentsVerification
verifyNew(java.lang.Class<T> mock, org.mockito.verification.VerificationMode mode)
Verifies certain behavior happened at least once / exact number of times / never.static void
verifyNoMoreInteractions(java.lang.Object... mocks)
Checks if any of given mocks (can be both instance and class mocks) has any unverified interaction.static PrivateMethodVerification
verifyPrivate(java.lang.Class<?> clazz)
Verify a private method invocation for a class.static PrivateMethodVerification
verifyPrivate(java.lang.Class<?> clazz, org.mockito.verification.VerificationMode verificationMode)
Verify a private method invocation for a class with a given verification mode.static PrivateMethodVerification
verifyPrivate(java.lang.Object object)
Verify a private method invocation for an instance.static PrivateMethodVerification
verifyPrivate(java.lang.Object object, org.mockito.verification.VerificationMode verificationMode)
Verify a private method invocation with a given verification mode.static <T> void
verifyStatic(java.lang.Class<T> mockedClass)
Verifies certain behavior of themockedClass
happened oncestatic <T> void
verifyStatic(java.lang.Class<T> mockedClass, org.mockito.verification.VerificationMode verificationMode)
Verifies certain behavior of themockedClass
happened at least once / exact number of times / never.static void
verifyZeroInteractions(java.lang.Object... mocks)
Verifies that no interactions happened on given mocks (can be both instance and class mocks).static <T> org.mockito.stubbing.OngoingStubbing<T>
when(java.lang.Class<?> klass, java.lang.Object... arguments)
Expect calls to private static methods without having to specify the method name.static <T> WithOrWithoutExpectedArguments<T>
when(java.lang.Class<?> cls, java.lang.reflect.Method method)
Expect calls to private static methods.static <T> org.mockito.stubbing.OngoingStubbing<T>
when(java.lang.Class<?> clazz, java.lang.String methodToExpect, java.lang.Object... arguments)
Expect a static private or inner class method call.static <T> org.mockito.stubbing.OngoingStubbing<T>
when(java.lang.Object instance, java.lang.Object... arguments)
Expect calls to private methods without having to specify the method name.static <T> WithOrWithoutExpectedArguments<T>
when(java.lang.Object instance, java.lang.reflect.Method method)
Expect calls to private methods.static <T> org.mockito.stubbing.OngoingStubbing<T>
when(java.lang.Object instance, java.lang.String methodName, java.lang.Object... arguments)
Expect calls to private methods.static <T> org.mockito.stubbing.OngoingStubbing<T>
when(T methodCall)
Just delegates to the originalMockito.when(Object)
method.static <T> ConstructorExpectationSetup<T>
whenNew(java.lang.Class<T> type)
Allows specifying expectations on new invocations.static <T> WithOrWithoutExpectedArguments<T>
whenNew(java.lang.reflect.Constructor<T> ctor)
Allows specifying expectations on new invocations.static <T> ConstructorExpectationSetup<T>
whenNew(java.lang.String fullyQualifiedName)
Allows specifying expectations on new invocations for private member (inner) classes, local or anonymous classes.-
Methods inherited from class org.powermock.api.support.membermodification.MemberModifier
replace, stub, suppress, suppress, suppress, suppress, suppress, suppress, suppress
-
Methods inherited from class org.powermock.api.support.membermodification.MemberMatcher
constructor, constructor, constructors, constructorsDeclaredIn, defaultConstructorIn, everythingDeclaredIn, field, fields, fields, fields, fields, method, method, methods, methods, methods, methodsDeclaredIn
-
-
-
-
Field Detail
-
POWERMOCKITO_CORE
private static final PowerMockitoCore POWERMOCKITO_CORE
-
-
Method Detail
-
mockStatic
public static void mockStatic(java.lang.Class<?> type, java.lang.Class<?>... types)
Enable static mocking for all methods of a class.- Parameters:
type
- the class to enable static mocking
-
mockStatic
public static void mockStatic(java.lang.Class<?> classMock, org.mockito.stubbing.Answer defaultAnswer)
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.
mockStatic(Foo.class, RETURNS_SMART_NULLS); mockStatic(Foo.class, new YourOwnAnswer());
- Parameters:
classMock
- class to mockdefaultAnswer
- default answer for unstubbed methods
-
mockStatic
public static void mockStatic(java.lang.Class<?> classToMock, org.mockito.MockSettings mockSettings)
Creates a class mock with some non-standard settings.The number of configuration points for a mock grows so we need a fluent way to introduce new configuration without adding more and more overloaded PowerMockito.mockStatic() methods. Hence
MockSettings
.mockStatic(Listener.class, withSettings() .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); );
Use it carefully and occasionally. What might be reason your test needs non-standard mocks? Is the code under test so complicated that it requires non-standard mocks? Wouldn't you prefer to refactor the code under test so it is testable in a simple way?
See also
Mockito.withSettings()
- Parameters:
classToMock
- class to mockmockSettings
- additional mock settings
-
mock
public static <T> T mock(java.lang.Class<T> type)
Creates a mock object that supports mocking of final and native methods.- Type Parameters:
T
- the type of the mock object- Parameters:
type
- the type of the mock object- Returns:
- the mock object.
-
mock
public static <T> T mock(java.lang.Class<T> classToMock, org.mockito.stubbing.Answer defaultAnswer)
Creates 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.
Foo mock = mock(Foo.class, RETURNS_SMART_NULLS); Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
See examples in javadoc for
Mockito
class- Parameters:
classToMock
- class or interface to mockdefaultAnswer
- default answer for unstubbed methods- Returns:
- mock object
-
mock
public static <T> T mock(java.lang.Class<T> classToMock, org.mockito.MockSettings mockSettings)
Creates a mock with some non-standard settings.The number of configuration points for a mock grows so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods. Hence
MockSettings
.Listener mock = mock(Listener.class, withSettings() .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); );
Use it carefully and occasionally. What might be reason your test needs non-standard mocks? Is the code under test so complicated that it requires non-standard mocks? Wouldn't you prefer to refactor the code under test so it is testable in a simple way?
See also
Mockito.withSettings()
See examples in javadoc for
Mockito
class- Parameters:
classToMock
- class or interface to mockmockSettings
- additional mock settings- Returns:
- mock object
-
spy
public static <T> T spy(T object)
Spy on objects that are final or otherwise not "spyable" from normal Mockito.- Type Parameters:
T
- the type of the mock object- Parameters:
object
- the object to spy on- Returns:
- the spy object.
- See Also:
spy(Object)
-
spy
public static <T> void spy(java.lang.Class<T> type)
Spy on classes (not "spyable" from normal Mockito).- Type Parameters:
T
- the type of the class mock- Parameters:
type
- the type of the class mock- See Also:
spy(Object)
-
verifyStatic
public static <T> void verifyStatic(java.lang.Class<T> mockedClass)
Verifies certain behavior of themockedClass
happened onceAlias to
verifyStatic(classMock, times(1))
E.g:verifyStatic(ClassWithStaticMethod.class); ClassWithStaticMethod.someStaticMethod("some arg");
Above is equivalent to:
verifyStatic(ClassWithStaticMethod.class, times(1)); ClassWithStaticMethod.someStaticMethod("some arg");
Although it is possible to verify a stubbed invocation, usually it's just redundant. Let's say you've stubbed foo.bar(). If your code cares what foo.bar() returns then something else breaks(often before even verify() gets executed). If your code doesn't care what get(0) returns then it should not be stubbed.
- Parameters:
mockedClass
- the mocked class behavior of that have to be verified.
-
verifyStatic
public static <T> void verifyStatic(java.lang.Class<T> mockedClass, org.mockito.verification.VerificationMode verificationMode)
Verifies certain behavior of themockedClass
happened at least once / exact number of times / never. E.g:verifyStatic(ClassWithStaticMethod.class, times(5)); ClassWithStaticMethod.someStaticMethod("was called five times"); verifyStatic(ClassWithStaticMethod.class, atLeast(2)); ClassWithStaticMethod.someStaticMethod("was called at least two times"); //you can use flexible argument matchers, e.g: verifyStatic(ClassWithStaticMethod.class, atLeastOnce()); ClassWithStaticMethod.someMethod(<b>anyString()</b>);
times(1) is the default and can be omitted
- Parameters:
mockedClass
- the mocked class behavior of that have to be verified.verificationMode
- times(x), atLeastOnce() or never()
-
verifyPrivate
public static PrivateMethodVerification verifyPrivate(java.lang.Object object)
Verify a private method invocation for an instance.- See Also:
Mockito.verify(Object)
-
verifyPrivate
public static PrivateMethodVerification verifyPrivate(java.lang.Object object, org.mockito.verification.VerificationMode verificationMode)
Verify a private method invocation with a given verification mode.- See Also:
Mockito.verify(Object)
-
verifyPrivate
public static PrivateMethodVerification verifyPrivate(java.lang.Class<?> clazz) throws java.lang.Exception
Verify a private method invocation for a class.- Throws:
java.lang.Exception
- If something unexpected goes wrong.- See Also:
Mockito.verify(Object)
-
verifyPrivate
public static PrivateMethodVerification verifyPrivate(java.lang.Class<?> clazz, org.mockito.verification.VerificationMode verificationMode)
Verify a private method invocation for a class with a given verification mode.- See Also:
Mockito.verify(Object)
-
verifyNew
public static <T> ConstructorArgumentsVerification verifyNew(java.lang.Class<T> mock)
Verifies certain behavior happened onceAlias to
verifyNew(mockClass, times(1))
E.g:verifyNew(ClassWithStaticMethod.class);
Above is equivalent to:
verifyNew(ClassWithStaticMethod.class, times(1));
- Parameters:
mock
- Class mocked by PowerMock.
-
verifyNew
public static <T> ConstructorArgumentsVerification verifyNew(java.lang.Class<T> mock, org.mockito.verification.VerificationMode mode)
Verifies certain behavior happened at least once / exact number of times / never. E.g:verifyNew(ClassWithStaticMethod.class, times(5)); verifyNew(ClassWithStaticMethod.class, atLeast(2)); //you can use flexible argument matchers, e.g: verifyNew(ClassWithStaticMethod.class, atLeastOnce());
times(1) is the default and can be omitted
- Parameters:
mock
- to be verifiedmode
- times(x), atLeastOnce() or never()
-
when
public static <T> org.mockito.stubbing.OngoingStubbing<T> when(java.lang.Object instance, java.lang.String methodName, java.lang.Object... arguments) throws java.lang.Exception
Expect calls to private methods.- Throws:
java.lang.Exception
- If something unexpected goes wrong.- See Also:
when(Object)
-
when
public static <T> WithOrWithoutExpectedArguments<T> when(java.lang.Object instance, java.lang.reflect.Method method)
Expect calls to private methods.- See Also:
when(Object)
-
when
public static <T> WithOrWithoutExpectedArguments<T> when(java.lang.Class<?> cls, java.lang.reflect.Method method)
Expect calls to private static methods.- See Also:
when(Object)
-
when
public static <T> org.mockito.stubbing.OngoingStubbing<T> when(java.lang.Object instance, java.lang.Object... arguments) throws java.lang.Exception
Expect calls to private methods without having to specify the method name. The method will be looked up using the parameter types (if possible).- Throws:
java.lang.Exception
- If something unexpected goes wrong.- See Also:
when(Object)
-
when
public static <T> org.mockito.stubbing.OngoingStubbing<T> when(java.lang.Class<?> clazz, java.lang.String methodToExpect, java.lang.Object... arguments) throws java.lang.Exception
Expect a static private or inner class method call.- Throws:
java.lang.Exception
- If something unexpected goes wrong.- See Also:
when(Object)
-
when
public static <T> org.mockito.stubbing.OngoingStubbing<T> when(java.lang.Class<?> klass, java.lang.Object... arguments) throws java.lang.Exception
Expect calls to private static methods without having to specify the method name. The method will be looked up using the parameter types if possible- Throws:
java.lang.Exception
- If something unexpected goes wrong.- See Also:
when(Object)
-
when
public static <T> org.mockito.stubbing.OngoingStubbing<T> when(T methodCall)
Just delegates to the originalMockito.when(Object)
method.- See Also:
when(Object)
-
whenNew
public static <T> WithOrWithoutExpectedArguments<T> whenNew(java.lang.reflect.Constructor<T> ctor)
Allows specifying expectations on new invocations. For example you might want to throw an exception or return a mock.
-
whenNew
public static <T> ConstructorExpectationSetup<T> whenNew(java.lang.Class<T> type)
Allows specifying expectations on new invocations. For example you might want to throw an exception or return a mock.
-
whenNew
public static <T> ConstructorExpectationSetup<T> whenNew(java.lang.String fullyQualifiedName) throws java.lang.Exception
Allows specifying expectations on new invocations for private member (inner) classes, local or anonymous classes. For example you might want to throw an exception or return a mock.- Parameters:
fullyQualifiedName
- The fully-qualified name of the inner/local/anonymous type to expect.- Throws:
java.lang.Exception
-
verifyNoMoreInteractions
public static void verifyNoMoreInteractions(java.lang.Object... mocks)
Checks if any of given mocks (can be both instance and class mocks) has any unverified interaction. Delegates to the originalMockito.verifyNoMoreInteractions(Object...)
if the mock is not a PowerMockito mock.You can use this method after you verified your mocks - to make sure that nothing else was invoked on your mocks.
See also
Mockito.never()
- it is more explicit and communicates the intent well.Stubbed invocations (if called) are also treated as interactions.
A word of warning: Some users who did a lot of classic, expect-run-verify mocking tend to use verifyNoMoreInteractions() very often, even in every test method. verifyNoMoreInteractions() is not recommended to use in every test method. verifyNoMoreInteractions() is a handy assertion from the interaction testing toolkit. Use it only when it's relevant. Abusing it leads to over-specified, less maintainable tests. You can find further reading here.
This method will also detect unverified invocations that occurred before the test method, for example: in setUp(), @Before method or in constructor. Consider writing nice code that makes interactions only in test methods.
Example:
//interactions mock.doSomething(); mock.doSomethingUnexpected(); //verification verify(mock).doSomething(); //following will fail because 'doSomethingUnexpected()' is unexpected verifyNoMoreInteractions(mock);
See examples in javadoc for
Mockito
class- Parameters:
mocks
- to be verified
-
verifyZeroInteractions
public static void verifyZeroInteractions(java.lang.Object... mocks)
Verifies that no interactions happened on given mocks (can be both instance and class mocks). Delegates to the originalverifyNoMoreInteractions(Object...)
if the mock is not a PowerMockito mock.verifyZeroInteractions(mockOne, mockTwo);
This method will also detect invocations that occurred before the test method, for example: in setUp(), @Before method or in constructor. Consider writing nice code that makes interactions only in test methods.
See also
Mockito.never()
- it is more explicit and communicates the intent well.See examples in javadoc for
Mockito
class- Parameters:
mocks
- to be verified
-
doAnswer
public static PowerMockitoStubber doAnswer(org.mockito.stubbing.Answer<?> answer)
Use doAnswer() when you want to stub a void method with genericAnswer
.Stubbing voids requires different approach from
when(Object)
because the compiler does not like void methods inside brackets...Example:
doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); Mock mock = invocation.getMock(); return null; } }).when(mock).someMethod();
See examples in javadoc for
Mockito
class- Parameters:
answer
- to answer when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
-
doThrow
public static PowerMockitoStubber doThrow(java.lang.Throwable toBeThrown)
Use doThrow() when you want to stub the void method with an exception.Stubbing voids requires different approach from
when(Object)
because the compiler does not like void methods inside brackets...Example:
doThrow(new RuntimeException()).when(mock).someVoidMethod();
- Parameters:
toBeThrown
- to be thrown when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
-
doCallRealMethod
public static PowerMockitoStubber doCallRealMethod()
Use doCallRealMethod() when you want to call the real implementation of a method.As usual you are going to read the partial mock warning: Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.
However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.
See also javadoc
spy(Object)
to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.Example:
Foo mock = mock(Foo.class); doCallRealMethod().when(mock).someVoidMethod(); // this will call the real implementation of Foo.someVoidMethod() mock.someVoidMethod();
See examples in javadoc for
Mockito
class- Returns:
- stubber - to select a method for stubbing
-
doNothing
public static PowerMockitoStubber doNothing()
Use doNothing() for setting void methods to do nothing. Beware that void methods on mocks do nothing by default! However, there are rare situations when doNothing() comes handy:1. Stubbing consecutive calls on a void method:
doNothing().doThrow(new RuntimeException()).when(mock).someVoidMethod(); //does nothing the first time: mock.someVoidMethod(); //throws RuntimeException the next time: mock.someVoidMethod();
2. When you spy real objects and you want the void method to do nothing:
List list = new LinkedList(); List spy = spy(list); //let's make clear() do nothing doNothing().when(spy).clear(); spy.add("one"); //clear() does nothing, so the list still contains "one" spy.clear();
See examples in javadoc for
Mockito
class- Returns:
- stubber - to select a method for stubbing
-
doReturn
public static PowerMockitoStubber doReturn(java.lang.Object toBeReturned)
Use doReturn() in those rare occasions when you cannot usewhen(Object)
.Beware that
when(Object)
is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).Here are those rare occasions when doReturn() comes handy:
1. When spying real objects and calling real methods on a spy brings side effects
List list = new LinkedList(); List spy = spy(list); //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn("foo"); //You have to use doReturn() for stubbing: doReturn("foo").when(spy).get(0);
2. Overriding a previous exception-stubbing:
when(mock.foo()).thenThrow(new RuntimeException()); //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. when(mock.foo()).thenReturn("bar"); //You have to use doReturn() for stubbing: doReturn("bar").when(mock).foo();
Above scenarios shows a trade off of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare.
See examples in javadoc for
Mockito
class- Parameters:
toBeReturned
- to be returned when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
-
doReturn
public static PowerMockitoStubber doReturn(java.lang.Object toBeReturned, java.lang.Object... othersToBeReturned)
Same asdoReturn(Object)
but sets consecutive values to be returned. Remember to usedoReturn()
in those rare occasions when you cannot usewhen(Object)
.Beware that
when(Object)
is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).Here are those rare occasions when doReturn() comes handy:
- When spying real objects and calling real methods on a spy brings side effects
List list = new LinkedList(); List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn("foo", "bar", "qix");
//You have to use doReturn() for stubbing: doReturn("foo", "bar", "qix").when(spy).get(0);
- Overriding a previous exception-stubbing:
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. when(mock.foo()).thenReturn("bar", "foo", "qix");
//You have to use doReturn() for stubbing: doReturn("bar", "foo", "qix").when(mock).foo();
Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overriding stubbing is a potential code smell that points out too much stubbing.
See examples in javadoc for
PowerMockito
class- Parameters:
toBeReturned
- to be returned when the stubbed method is calledothersToBeReturned
- to be returned in consecutive calls when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
- Since:
- 1.6.5
- When spying real objects and calling real methods on a spy brings side effects
-
-