Friday, October 24, 2008

Mock Example

Mocking is a great way to test a class in isolation. Not only can determinisitic results of the mocked class be forced, but parameters to the mocked object's methods can be tested.

Here is a unit test that uses mockito as its mocking framework. It is organized in the increasingly popular Arrange / Act / Assert format. This tests a yet to be written subclass of Spring's AbstractJDomPayloadEndpoint.

  1 @Test
2 public void validDepthOfField( ) throws Exception {
3 stub( _depthOfFieldCalculator.calculateDepthOfField( _expectedDofParams ) ).toReturn( _depthOfField );
5 final PhotoEndpoint photoEndpoint =
6 new PhotoEndpoint( _depthOfFieldCalculator );
7 final Element dofElem =
8 photoEndpoint.invokeInternal( _depthOfFieldRequest );
10 Assert.assertEquals( _depthOfField.getFarLimit(),
11 _parseDouble( dofElem, _farLimitExpression));
12 Assert.assertEquals( _depthOfField.getNearLimit(),
13 _parseDouble(dofElem, _nearLimitExpression));
14 Assert.assertEquals( _depthOfField.getHyperFocalDistance(),
15 _parseDouble(dofElem, _hyperFocusDistanceExpression));
16 }

  • Line 3: _depthOfFieldCalculator was mocked with mockito in JUnit's @Before. If calculateDepthOfField(...) is called with a object matching _expectedDofParams(equals overridden), _depthOfField will be returned. Important to note that if the calculateDepthOfField is called with the wrong parameter, the mock will return null.
  • Lines 5-6: Create a class that does not yet exist with our mock.
  • Lines 7-8: Call the endpoint's invoke method that is under test.
  • Lines 10-15: Assert that the returned Element is valid.

Labels: , ,

Comments: Post a Comment

Subscribe to Post Comments [Atom]

<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]