package sis.db; import junit.framework.*; import java.io.*; import sis.util.*; public class DataFileTest extends TestCase { private static final String ID1 = "12345"; private static final String ID2 = "23456"; private static final String FILEBASE = "DataFileTest"; private DataFile db; private TestData testData1; private TestData testData2; protected void setUp() throws IOException { db = DataFile.create(FILEBASE); assertEquals(0, db.size()); testData1 = new TestData(ID1, "datum1a", 1); testData2 = new TestData(ID2, "datum2a", 2); } protected void tearDown() throws IOException { db.close(); db.deleteFiles(); } public void testAdd() throws IOException { db.add(ID1, testData1); assertEquals(1, db.size()); db.add(ID2, testData2); assertEquals(2, db.size()); assertTestDataEquals(testData1, (TestData)db.findBy(ID1)); assertTestDataEquals(testData2, (TestData)db.findBy(ID2)); } public void testPersistence() throws IOException { db.add(ID1, testData1); db.add(ID2, testData2); db.close(); db = DataFile.open(FILEBASE); assertEquals(2, db.size()); assertTestDataEquals(testData1, (TestData)db.findBy(ID1)); assertTestDataEquals(testData2, (TestData)db.findBy(ID2)); db = DataFile.create(FILEBASE); assertEquals(0, db.size()); } public void testKeyNotFound() throws IOException { assertNull(db.findBy(ID2)); } private void assertTestDataEquals( TestData expected, TestData actual) { assertEquals(expected.id, actual.id); assertEquals(expected.field1, actual.field1); assertEquals(expected.field2, actual.field2); } static class TestData implements Serializable { String id; String field1; int field2; TestData(String id, String field1, int field2) { this.id = id; this.field1 = field1; this.field2 = field2; } } } DataFileTest shows that you create a new DataFile using the static factory method create. The create method takes the name of the DataFile as its parameter. The test also shows that you insert objects into a DataFile by using the add method, which takes a unique key and associated object as parameters. To retrieve objects, you send the message findBy, passing with it the unique id of the object to be retrieved. If the object is not available, DataFile returns null. Persistence is tested by closing a DataFile and creating a new instance using the static factory method open.[3] The distinction between open and create is that create will delete the data file if it already exists, while open will reuse an existing data file or create a new one if necessary.
Note that the object returned by the findBy method requires a cast! This suggests that DataFile is a candidate for implementing as a parameterized type. (See Lesson 14 for more information on parameterized types.) |