Presentation is loading. Please wait.

Presentation is loading. Please wait.

Eddie Jaquith Alexis Jarvis

Similar presentations


Presentation on theme: "Eddie Jaquith Alexis Jarvis"— Presentation transcript:

1 Eddie Jaquith Alexis Jarvis
and PowerMock Eddie Jaquith Alexis Jarvis

2 What is Mockito? It is a testing framework that tastes GOOD!
Alternative to Jmock Concept of mocks as placeholders to actual object interactions Designed to be lightweight so you only code interactions when you need them

3 Mocks As In

4 Mocks Not

5 Enter… The PowerMock framework extends a number of other test frameworks (not just Mockito) Mockito’s PowerMock framework is called PowerMockito Intended for legacy projects Mock object injection support Capable of final, private and static mocking MORE ON THESE LATER!

6 Components of a Test Case

7 Four easy steps! Data preparation Mock expectation setup
Test method execution AND LAST BUT DEFINITELY NOT LEAST… Verification!

8 Mocks Instantiation can be done in one of two ways
Mockito mock() method Annotation on member variable

9 Mocks Mocks are objects you depend on for return values, delegated processing Used for when you don’t want to directly test

10 Mocks Example: If I am testing a method called dropDatabase() that takes in a String as a SID, I only want to test the fact that this method verifies the SID to be a certain value, not actually interact with any databases. Mocks allow you to do that by mimicking the signature of a method, but not invoking any actual code You control Exception flow and return types based on parameters passed in using expectations

11 Spies Spies are the inverse of mocks
i.e. all methods are regularly invoked unless they are stubbed Used to test large classes with dependencies that exist within the class

12 Spies Are instantiated the same way as Mocks (i.e. either through annotations or the spy() static method) Utilizes the doNothing() expectation in order to not call real void return type methods

13 Spies These expectations will not call real methods
Real isNewLicense() method is called here

14 Expectations Expectations are the major mechanism in which behavior on mocked instances is determined Concept of when(conditions) then(return results) Ex. when(mockSandwichShop.getSandwich(“yummy”)) .thenReturn(yummySandwich)

15 Expectations Supports explicit and matching conditions
Explicit conditions mean that the methods need to be called with those exact parameters Think literals and object instances Using the following will ONLY return 25 when 1, “Bus” and 60 is passed in: when(mockedRadar.detectSpeed(1, “Bus”, 60)).thenReturn(25) Any invocations to detectSpeed() that do not match these parameters will fall back to the default behavior of the mocked object (typically return null)

16 Expectations Supports explicit and matching conditions
Matching conditions mean that the methods can be called with any parameters meeting the criteria provided Note that all parameters must be Matchers when using matching Using the following will return 25 whenever “Bus” is passed in along with any numbers: when(mockedRadar.detectSpeed(anyInt(), eq(“Bus”), anyInt())).thenReturn(25) Note that in order to match a literal (“Bus”), you need to use the eq() Matcher Fun fact, this is Hamcrest working behind the scenes!

17 Expectations Some helpful matcher methods include anyString()
any(Some.class) any() anyList() anyCollection() many more, see Matchers.java in the Mockito library!

18 Mock behavior Default behavior of unconfigured interactions with a mock is configurable Default behavior is to return null Smart nulls return SmartNullPointerException, which can be used to track down the line easier via a stack trace Returns mocks will attempt to return a mock object instance Returns deep stubs allows for mocks to be returned except for the last mock on a chain Very useful if you have chains of objects where all you care about is the last method!

19 Mock behavior RETURNS_DEFAULTS
Unstubbed call on the mock UserToken object Result: NullPointerException on getCustomer().getId() as Customer is null

20 Mock behavior RETURNS_SMART_NULLS
Unstubbed calls on the mock UserToken object Result: SmartNullPointerException on getCustomer().getId() as Customer is null Will be easier to read exception on log output

21 Mock behavior RETURNS_MOCKS
Unstubbed calls on the mock UserToken object Result: getId returns 0, but any more complicated gets will return mocks

22 Mock behavior RETURNS_DEEP_STUBS
Unstubbed calls on the mock UserToken object Result: getId returns 0, but the getId() method can be further stubbed to return meaningful output E.g. the below line will allow the above line to return the integer 23

23 Mock behavior CALLS_REAL_METHODS
Unstubbed call on the mock UserToken object Result: NullPointerException, since the Customer object on the UserToken object is null (the real get methods are called here) This behavior is the same as when you spy an object

24 Verification Once your test method has been invoked you can then verify your test using one of a number of ways Junit Asserts (e.g. assertEquals(), assertNull(), …) Hamcrest Matchers (assertThat() ) Mockito verify() Exceptions = ValidationException.class))

25 Verification Keep in mind you can verify not only your returned object from your calling methods, but any objects you have injected using expectations as well! E.g. verify private method behavior by observing modifications to input objects, mocked expectation returns, etc.

26 Verification – verify()
The verify() method will ensure that a method has been called 0, 1 or many times By default, using verify() will test for one invocation exactly, but can be passed times(int number) as an additional argument to control 0 or many invocations

27 Verification – verify()
verify() failures result in output-friendly messages Wanted but not invoked: maintainContinuingEducationFacade.changeProviderStatus (<arguments>); -> at com.iits.mb.app.delegate.MaintainContinuingEducationDe legateTest.testChangeProviderPEStatus_activateFailsRes trictionCheck(MaintainContinuingEducationDelegateTest. java:303) Actually, there were zero interactions with this mock. <Full Stacktrace follows>

28 Verification – verify()
E.g. expect that changeProviderStatus is never called with a specific userToken and provider verify(getMockMaintainContinuingEducationFacade(), times(0)) .changeProviderStatus(getMockUserToken(), provider);

29 Verification – verify()
You should never verify a method that has already been stubbed with an expectation as they do the same thing! If you stub a method, you control it, you should only use verify to test methods outside your direct control Good for testing code flow based on data based decisions (e.g. façade call was made even though we aren’t testing facade code)

30 Using PowerMock In addition to using the PowerMock libraries, a custom classloader is needed to run PowerMock test cases Done by adding the following annotation to your test class: @RunWith(PowerMockRunner.class) Protip: You can add this just once to a super class of all your test classes!

31 Using PowerMock – Static usage
In order to mock static classes or methods, the class needs to be prepared in your test case’s setup mockStatic(Class class) for the particular class @PrepareForTest annotation for the class you wish to use This will allow the custom classloader to add PowerMock code to the compiled classes

32 Using PowerMock – Static usage
Static expectations work a little differently than normal expectations If you don’t have a return type, then no expectations are needed A doNothing() does exist, but is rarely useful You can set up an exception with the doThrow() method Calling signature is different when there is no return type doThrow(new ValidationException()).when(MbProviderValidator.class, "validateProviderRestrictedByFunction", getMockUserToken(), providerCourse.getProvider(), ISecurityCodes.PROVIDER_COURSE_ACTIVATION);

33 Using PowerMock – Static usage
Verifies follow a slightly different syntax Need to call verifyStatic() immediately prior to invoking static method verifyStatic(); MbProviderValidator.validateProviderRestrictedByFunction( getMockUserToken(), application.getMbProvider(), ISecurityCodes.PROVIDER_COURSE_APPLICATION_APPROVAL); Can also use times(0) as an argument to verify NO interactions with a static method occurred

34 Using PowerMock – Final usage
Similar to static, where you need to include @PrepareForTest so the custom classloader can prepare the class Can then add expectations like a normal class

35 Using PowerMock – Constructor Injection
Another powerful tool in legacy products is the ability to inject objects where the new keyword is used – the whenNew() method In order to properly use constructor injection, you must provide the calling class inside annotation E.g., if a SemanticValidator creates an object you wish to inject, you must in your test class

36 Using PowerMock – Constructor Injection
Sample Usage whenNew(MaintainRestrictionsDelegate.class) .withArguments(getMockUserToken()) .thenReturn(getMockMaintainRestrictionsDelegate()); withNoArguments() is used when a default constructor is needed

37 Testing Strategies

38 Testing Strategies Only mock behavior you actually need (and mock every dependency) Actually use your mocked objects to verify post execution behavior Working with (despite) private methods Name your methods appropriately DRY principles

39 Protips Homegrown PowerMock helper methods
private void validatePrepareForTestAnnotation(Class className) { PrepareForTest prepareForTestAnnotation = this.getClass().getAnnotation(PrepareForTest.class); PulsarSystemException pulsarSystemException = new PulsarSystemException(“Cannot mock static method. " "Your code appears to be missing required PrepareForTest annotation for " className.toString() + ". Please add it to annotation!"); if (prepareForTestAnnotation == null) { throw pulsarSystemException; } List<Class<?>> preparedClasses = Arrays.asList(prepareForTestAnnotation.value()); if (!CommonUtils.isValid(preparedClasses) || !preparedClasses.contains(className)) { throw pulsarSystemException; } }

40 Protips Homegrown PowerMock helper methods
private void validateStaticClassPrepared(Class classToValidate) { validatePrepareForTestAnnotation(classToValidate); Boolean isPrepared = staticClassPrepared.get(classToValidate); if (isPrepared == null || !isPrepared) { //This should be called by the test case, but we'll let it slide mockStatic(classToValidate, RETURNS_SMART_NULLS); staticClassPrepared.put(classToValidate, true); System.err.println(classToValidate + " not prepared properly. Preparing for you this time, " "but fix it next time! Add the following line to your code: \n prepareForMockStaticUsage(" classToValidate + ".class)"); } }

41 Protips PowerMock and Cobertura in test builds Finally…
Make sure to use @PowerMockIgnore(“net.sourceforge.cobertura.*”) Finally… Read the documentation in the provided source code! You will learn something, I promise!

42 Resources http://mockito.org/
wiki/MockitoUsage

43 Questions?


Download ppt "Eddie Jaquith Alexis Jarvis"

Similar presentations


Ads by Google