The framework encourages a layered architecture, which implies a layered approach to testing. Now that we have a presentation layer up and running, we can look at interacting with the business layer. Unit tests are a great way to explore how a software component works. How can unit tests do interact with the database? How can a test show us how to find an account or add a new account?
Presentation - JUnit Jumpstart
Why do we test applications? How do we test applications? Why do we need a testing framework? How do we get started with JUnit?
We explore the industry-standard testing framework, JUnit.
- Writing simple tests by hand
- Writing better tests with JUnit
- Installing JUnit and running tests
Workshop - Retain
Story: MailReader profiles and subscriptions are stored for later retrieval.
- Create unit tests for business code
- Learn how to use the business code API
Prerequisites
- TestCase
- setUp
- assertNull, assertNotNull, assertSame
New Dependencies
- Collections
- Digester
- BeanUtils
- Mailreader DAO
Exercises
- Continue using your own solution or create a new module using the "hello" solution on the CD.
- Review the Retain use case.
- Create a RetainTest case that exercises the database methods shown in the Retain Narrative.
Hint Code
Here's a setUp method and a test for the first statement.
import junit.framework.TestCase; import org.apache.struts.apps.mailreader.dao.User; import org.apache.struts.apps.mailreader.dao.UserDatabase; import org.apache.struts.apps.mailreader.dao.impl.memory.MemoryUserDatabase; public class RetainTest extends TestCase { protected UserDatabase userDatabase; protected String testName = "test-database.xml"; public void setUp() throws Exception { super.setUp(); MemoryUserDatabase memoryUserDatabase = new MemoryUserDatabase(); memoryUserDatabase.setPathname(testName); userDatabase = memoryUserDatabase; } public void testDatabaseClean() throws Exception { User user = userDatabase.findUser("user"); assertNull("Expected user to be created",user); } // Add your test methods here. // The setUp method will run between each test. }
Here's the syntax for some key assertions:
assertNull("Expected user to be created", user);
assertNotNull(user);
assertSame("Expected users to match", user1, user2);
Accomplishments
- Created unit tests for business code
- Learned how to use the business code API
Extra Credit
- Read the database back after saving it and confirm that the save persisted your changes.
- Write tests to confirm failures like "User not found" and "Subscription not found"
- Write a test that creates ten users and verify each was created
