Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.

Similar presentations


Presentation on theme: "Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing."— Presentation transcript:

1 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing without Spring, and Integration Testing with Spring

2 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2 Topics in this session Test Driven Development Unit Testing vs. Integration Testing Unit Testing with Stubs Unit Testing with Mocks Integration Testing with Spring

3 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3 Test Driven Development Unit Testing vs. Integration Testing Unit Testing with Stubs Unit Testing with Mocks Integration Testing with Spring Topics in this session

4 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4 What is TDD TDD = Test Driven Development Is it writing tests before the code? Is it writing tests at the same time as the code? That is not what is most important Do not get hung up on terminology Ultimately, TDD is about writing automated tests that verify code actually works

5 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5 “But I Don’t Have Time to Write Tests!” Every development process includes testing Either automated or manual Automated tests result in a faster development cycle overall Compare the time required to run a test in your IDE (seconds) vs. the time required for someone to manually follow a script (typically minutes/hours)

6 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6 TDD and Agility Comprehensive test coverage provides confidence Confidence enables refactoring Refactoring is essential to agile development

7 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7 TDD and Design Testing makes you think about your design If your code is hard to test then the design should be reconsidered

8 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8 Benefits of Continuous Integration The cost to fix a bug grows exponentially in proportion to the time before it is discovered Continuous Integration (CI) focuses on reducing the time before the bug is discovered Effective CI requires automated tests time to fix time until discovered

9 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9 Test Driven Development Unit Testing vs. Integration Testing Unit Testing with Stubs Unit Testing with Mocks Integration Testing with Spring Topics in this session

10 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10 Unit Testing vs. Integration Testing Unit Testing –Tests one unit of functionality –Keeps dependencies minimal –Isolated from the environment (including Spring) Integration Testing –Tests the interaction of multiple units working together –Integrates infrastructure

11 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11 Unit Testing Verify a unit works in isolation –If A depends on B, A’s tests should not fail because of a bug in B –A’s test should not pass because of a bug in B Stub or mock out dependencies if needed Have each test exercise a single scenario A path through the unit

12 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12 Example Unit to be Tested public class AuthenticatorImpl implements Authenticator { private AccountDao accountDao; public AuthenticatorImpl(AccountDao accountDao) { this.accountDao = accountDao; } public boolean authenticate(String username, String password) { Account account = accountDao.getAccount(username); if (account.getPassword().equals(password)) { return true; } else { return false; } public class AuthenticatorImpl implements Authenticator { private AccountDao accountDao; public AuthenticatorImpl(AccountDao accountDao) { this.accountDao = accountDao; } public boolean authenticate(String username, String password) { Account account = accountDao.getAccount(username); if (account.getPassword().equals(password)) { return true; } else { return false; } External dependencyUnit business logic (2 paths)

13 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13 Test Driven Development Unit Testing vs. Integration Testing Unit Testing with Stubs Unit Testing with Mocks Integration Testing with Spring Topics in this session

14 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14 Implementing a Stub class StubAccountDao implements AccountDao { private Map accountsByUsername = new HashMap(); public StubAccountDao() { accountsByUsername.put(“lisa”, new Account(“lisa”, “secret”)); } public Account getAccount(String user) { return (Account) accountsByUsername.get(user); } class StubAccountDao implements AccountDao { private Map accountsByUsername = new HashMap(); public StubAccountDao() { accountsByUsername.put(“lisa”, new Account(“lisa”, “secret”)); } public Account getAccount(String user) { return (Account) accountsByUsername.get(user); } Sets up state for testing

15 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15 Testing with a Stub public class AuthenticatorImplTests extends TestCase { private AuthenticatorImpl authenticator; public void setUp() { authenticator = new AuthenticatorImpl(new StubAccountDao()); } public void testSuccessfulAuthentication() { assertTrue(authenticator.authenticate(“lisa”, “secret”)); } public void testInvalidPassword() { assertFalse(authenticator.authenticate(“lisa”, “invalid”)); } public class AuthenticatorImplTests extends TestCase { private AuthenticatorImpl authenticator; public void setUp() { authenticator = new AuthenticatorImpl(new StubAccountDao()); } public void testSuccessfulAuthentication() { assertTrue(authenticator.authenticate(“lisa”, “secret”)); } public void testInvalidPassword() { assertFalse(authenticator.authenticate(“lisa”, “invalid”)); } Stub is configured Scenarios are exercised based on the state of stub

16 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16 Stub Considerations Advantages Easy to implement and understand Reusable Disadvantages A change to the interface requires the stub to be updated Your stub must implement all methods, even those not used by a specific scenario

17 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17 Test Driven Development Unit Testing vs. Integration Testing Unit Testing with Stubs Unit Testing with Mocks Integration Testing with Spring Topics in this session

18 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18 Steps to Testing with a Mock 1.Use a mocking library to generate a mock object Implements the dependent interface on-the-fly 2.Record the mock with expectations of how it will be used for a scenario What methods will be called What values to return 3.Exercise the scenario 4.Verify mock expectations were met

19 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19 The Easy Mock Library EasyMock 2.0 is best mocking library available Used extensively in Spring for unit testing What is taught in this course

20 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20 Example - Testing with EasyMock On setup 1.Create mock(s) 2.Create unit For each test 1.Record expected method calls and set mock return values 2.Call replay 3.Exercise test scenario 4.Call verify public class AuthenticatorImplTests extends TestCase { private AuthenticatorImpl authenticator; private AccountDao accountDao; protected void setUp() { accountDao = EasyMock.createMock(AccountDao.class); authenticator = new AuthenticatorImpl(accountDao); } public void testValidUserWithCorrectPassword() { EasyMock.expect(accountDao.getAccount(“lisa”)). andReturn(new Account(“lisa”, “secret”)); EasyMock.replay(accountDao); assertTrue(authenticator.authenticate(“lisa”, “secret”)); EasyMock.verify(accountDao); } public class AuthenticatorImplTests extends TestCase { private AuthenticatorImpl authenticator; private AccountDao accountDao; protected void setUp() { accountDao = EasyMock.createMock(AccountDao.class); authenticator = new AuthenticatorImpl(accountDao); } public void testValidUserWithCorrectPassword() { EasyMock.expect(accountDao.getAccount(“lisa”)). andReturn(new Account(“lisa”, “secret”)); EasyMock.replay(accountDao); assertTrue(authenticator.authenticate(“lisa”, “secret”)); EasyMock.verify(accountDao); } }

21 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21 Mock Considerations Advantages No additional class to maintain You only need to setup what is necessary for the scenario you are testing Disadvantages Harder to understand Changing unit internals often breaks your tests

22 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22 Mocks or Stubs? You will probably use both General recommendations Favor stubs in most situations Use mocks when stubs are impractical Always consider the specific situation Read “Mocks Aren’t Stubs” by Martin Fowler http://www.martinfowler.com/articles/mocksArentStubs.html

23 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23 Test Driven Development Unit Testing vs. Integration Testing Unit Testing with Stubs Unit Testing with Mocks Integration Testing with Spring Topics in this session

24 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24 Integration Testing Tests the interaction of multiple units Tests application classes in the context of their surrounding infrastructure Infrastructure may be “scaled down”

25 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25 Located in spring-mock.jar Consists of several JUnit test support classes Central support class is AbstractDependencyInjectionSpringContextTests Extends JUnit TestCase Loads system test configuration from one or more XML bean definition files Caches a shared ApplicationContext across multiple test methods Resolves test dependencies Spring’s Integration Test Support

26 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26 Using Spring’s Integration Test Support public final class AuthenticatorTests extends AbstractDependencyInjectionSpringContextTests { private Authenticator authenticator; @Override protected String[] getConfigLocations() { return new String[] { “classpath:system-test-config.xml” }; } public void setAuthenticator(Authenticator authenticator) { this.authenticator = authenticator; } public void testSuccessfulAuthentication() { authenticator.authenticate(...);... } public final class AuthenticatorTests extends AbstractDependencyInjectionSpringContextTests { private Authenticator authenticator; @Override protected String[] getConfigLocations() { return new String[] { “classpath:system-test-config.xml” }; } public void setAuthenticator(Authenticator authenticator) { this.authenticator = authenticator; } public void testSuccessfulAuthentication() { authenticator.authenticate(...);... } Extend support class Point to system test configuration file Define a dependency on the system entry pointTest the system as normal

27 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27 JUnit Test Runner AuthenticatorTests ClassPathXmlApplicationContext setUp (first time only) getConfigLocations() new(configLocations) Assigned to the protected field named applicationContext setAuthenticator(Authenticator) autowireBeanProperties(this) Calls each setter the context can satisfy by type Test Case Setup (first time only)

28 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28 Benefits of Integration Testing with Spring No need to deploy to an external container to test application functionality Run everything quickly inside your IDE Allows reuse of your configuration between test and production environments Application configuration logic is typically reused Infrastructure configuration is environment-specific DataSources JMS Queues

29 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29 Summary Testing is an essential part of any development Unit testing tests a class in isolation where external dependencies should be minimized Consider creating stubs or mocks to unit test You don’t need Spring to unit test Integration testing tests the interaction of multiple units working together Spring provides good integration testing support

30 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. LAB Testing Spring Applications


Download ppt "Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing."

Similar presentations


Ads by Google