KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > nutch > io > TestWritable


1 /* Copyright (c) 2003 The Nutch Organization. All rights reserved. */
2 /* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
3
4 package net.nutch.io;
5
6 import java.io.*;
7 import java.util.Random JavaDoc;
8 import junit.framework.TestCase;
9 import net.nutch.io.*;
10
11 /** Unit tests for Writable. */
12 public class TestWritable extends TestCase {
13   public TestWritable(String JavaDoc name) { super(name); }
14
15   /** Example class used in test cases below. */
16   public static class SimpleWritable implements Writable {
17     private static final Random JavaDoc RANDOM = new Random JavaDoc();
18
19     int state = RANDOM.nextInt();
20
21     public void write(DataOutput out) throws IOException {
22       out.writeInt(state);
23     }
24
25     public void readFields(DataInput in) throws IOException {
26       this.state = in.readInt();
27     }
28
29     public static SimpleWritable read(DataInput in) throws IOException {
30       SimpleWritable result = new SimpleWritable();
31       result.readFields(in);
32       return result;
33     }
34
35     /** Required by test code, below. */
36     public boolean equals(Object JavaDoc o) {
37       if (!(o instanceof SimpleWritable))
38         return false;
39       SimpleWritable other = (SimpleWritable)o;
40       return this.state == other.state;
41     }
42   }
43
44   /** Test 1: Check that SimpleWritable. */
45   public void testSimpleWritable() throws Exception JavaDoc {
46     testWritable(new SimpleWritable());
47   }
48
49   /** Utility method for testing writables. */
50   public static void testWritable(Writable before) throws Exception JavaDoc {
51       DataOutputBuffer dob = new DataOutputBuffer();
52       before.write(dob);
53
54       DataInputBuffer dib = new DataInputBuffer();
55       dib.reset(dob.getData(), dob.getLength());
56     
57       Writable after = (Writable)before.getClass().newInstance();
58       after.readFields(dib);
59
60       assertEquals(before, after);
61   }
62     
63 }
64
Popular Tags