際際滷

際際滷Share a Scribd company logo
+
Using JMock
By Jeff Dilley
+
Unit Testing
 Whats a unit?
 Code Isolation is important
 Code needs to be testable
+
jMock
 Used with jUnit
 Handles classes that rely on dependency injection / IOC
 Helps further isolate testing
+
jMock
 Expectations
 One(userService).getUser(someUserId);
will(returnValue(any(User.class))));
+
jMock
mockCtx.checking(new Expectations() {{
one(jSONServiceHelper).checkSession(request); will(returnValue(true));
exactly(2).of(request).getSession(); will(returnValue(session));
one(jSONServiceHelper).retriveCartVOFromSession(session); will(returnValue(cartVO));
one(jSONCartProcessingService).getProductDetails(price, prodId, duns); will(returnValue(tempCartVO));
one(jSONCartProcessingService).processShoppingCart(cartVO); will(returnValue(cartVO));
atLeast(1).of(session).setAttribute(WebCartConstants.WEBSALES_SESSION_CART, cartVO);
}});

More Related Content

Jmock testing

Editor's Notes

  • #3: Unit testing. Whats a unit? A unit is specific isolated functionality. An example: UserService.CreateUser(); UserService.UpdateUser(); Code uses other code. Sometimes two units of code depend on each other. Having the ability to test one unit without having to test the other is important. Tests should not depend on each other even if the code does. Good code is easy to test. If a test is getting extremely overly complex, its usually because the code being tested is overly complex and might need to be refactored. Proper use of interfaces (dependency injection) and setters and OOP in general will help with this.
  • #4: jMock is used with jUnit. jUnits assertion library works well with jMock. AssertTrue, AssertEqual, AssertNotNull Classes that use dependency injection (inversion of control) for accessing services, daos, etc. can be injected with mock objects instead. What happens if the code im testing uses an external service that needs to perform some functionality like return a new object, a modified object, etc.? Mock objects can be configured to expect certain values and configured to return certain values. This allows tests to be consistent and helps isolate the test by nullifying external functionality.
  • #5: jMock provides an interface Expectations for mocking external behavior. It provides a flexible API for setting up expectations. Take a look at this example. A usersService.getUser will be called once. It will be passed a userId value and will return any object as long it is of type User You can also use jMock to check, with assertions, that values being passed to a mocked object are correct. You can then pass specific values back from the mocked object to the tested object and verify the tested object acts on the specific values as expected.