Java Code Examples for junit.framework.TestCase

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project apb, under directory /modules/apb/src/apb/testrunner/.

Source file: JUnit3TestSet.java

  35 
vote

/** 
 * This is an ugly hack to filter-out useless TestSuites
 */
private static boolean isValidSuite(TestSuite testSuite){
  final int testCount=testSuite.testCount();
  if (testCount != 1) {
    return testCount > 1;
  }
  final Test test=testSuite.testAt(0);
  if (!(test instanceof TestCase)) {
    return true;
  }
  final TestCase testCase=(TestCase)test;
  return !"warning".equals(testCase.getName()) || !testCase.getClass().getName().startsWith("junit.framework.");
}
 

Example 2

From project jena-tdb, under directory /src/test/java/com/hp/hpl/jena/tdb/junit/.

Source file: TestFactoryTDB.java

  32 
vote

@Override protected Test makeTest(Resource manifest,Resource entry,String testName,Resource action,Resource result){
  if (testRootName != null)   testName=testRootName + testName;
  TestItem testItem=TestItem.create(entry,null,Syntax.syntaxARQ,DataFormat.langXML);
  TestCase test=null;
  if (testItem.getTestType() != null) {
    if (testItem.getTestType().equals(TestManifestX.TestQuery))     test=new QueryTestTDB(testName,report,testItem,factory);
    if (testItem.getTestType().equals(TestManifestX.TestSurpressed))     test=new SurpressedTest(testName,report,testItem);
    if (test == null)     System.err.println("Unrecognized test type: " + testItem.getTestType());
  }
  if (test == null)   test=new QueryTestTDB(testName,report,testItem,factory);
  return test;
}
 

Example 3

From project log4jna, under directory /thirdparty/junit/junit/tests/extensions/.

Source file: ExtensionTest.java

  32 
vote

public void testRunningErrorInTestSetup(){
  TestCase test=new TestCase("failure"){
    @Override public void runTest(){
      fail();
    }
  }
;
  TestSetup wrapper=new TestSetup(test);
  TestResult result=new TestResult();
  wrapper.run(result);
  assertTrue(!result.wasSuccessful());
}
 

Example 4

From project Cafe, under directory /testrunner/src/com/baidu/cafe/junitreport/.

Source file: JUnitReportListener.java

  31 
vote

@Override public void startTest(Test test){
  try {
    openIfRequired(test);
    if (test instanceof TestCase) {
      TestCase testCase=(TestCase)test;
      checkForNewSuite(testCase);
      mSerializer.startTag("",TAG_CASE);
      mSerializer.attribute("",ATTRIBUTE_CLASS,mCurrentSuite);
      mSerializer.attribute("",ATTRIBUTE_NAME,testCase.getName());
      mTimeAlreadyWritten=false;
      mTestStartTime=System.currentTimeMillis();
    }
  }
 catch (  IOException e) {
    Log.e(LOG_TAG,safeMessage(e));
  }
}
 

Example 5

From project Gemini-Blueprint, under directory /test-support/src/main/java/org/eclipse/gemini/blueprint/test/internal/support/.

Source file: OsgiJUnitService.java

  31 
vote

/** 
 * Run fixture setup, test from the given test case and fixture teardown.
 * @param osgiTestExtensions
 * @param testName
 */
protected TestResult runTest(final OsgiJUnitTest osgiTestExtensions,String testName){
  if (log.isDebugEnabled())   log.debug("Running test [" + testName + "] on testCase "+ osgiTestExtensions);
  final TestResult result=new TestResult();
  TestCase rawTest=osgiTestExtensions.getTestCase();
  rawTest.setName(testName);
  try {
    osgiTestExtensions.osgiSetUp();
    try {
      result.runProtected(rawTest,new Protectable(){
        public void protect() throws Throwable {
          osgiTestExtensions.osgiRunTest();
        }
      }
);
    }
  finally {
      osgiTestExtensions.osgiTearDown();
    }
  }
 catch (  Exception ex) {
    log.error("test exception threw exception ",ex);
    result.addError((Test)rawTest,ex);
  }
  return result;
}
 

Example 6

From project hbase-rdf_1, under directory /src/test/java/com/talis/hbase/rdf/test/query/.

Source file: TestQueryHBaseRdfFactory.java

  31 
vote

@Override public Test makeTest(Resource manifest,Resource entry,String testName,Resource action,Resource result){
  Syntax querySyntax=getQuerySyntax(manifest);
  if (testRootName != null)   testName=testRootName + testName;
  if (querySyntax != null) {
    if (!querySyntax.equals(Syntax.syntaxRDQL) && !querySyntax.equals(Syntax.syntaxARQ) && !querySyntax.equals(Syntax.syntaxSPARQL))     throw new QueryTestException("Unknown syntax: " + querySyntax);
  }
  Resource defaultTestType=getResource(manifest,TestManifestX.defaultTestType);
  TestItem testItem=TestItem.create(entry,defaultTestType,querySyntax,DataFormat.langXML);
  TestCase test=null;
  if (testItem.getTestType() != null) {
    if (testItem.getTestType().equals(TestManifestX.TestQuery))     test=new TestQueryHBaseRdf(storeDesc,testName,results,testItem);
    if (testItem.getTestType().equals(TestManifestX.TestSurpressed))     test=new SurpressedTest(testName,results,testItem);
    if (test == null)     System.err.println("Unrecognized test type: " + testItem.getTestType());
  }
  if (test == null)   test=new TestQueryHBaseRdf(storeDesc,testName,results,testItem);
  Resource action2=testItem.getAction();
  if (action2.hasProperty(TestManifestX.option))   System.out.println("OPTION");
  return test;
}
 

Example 7

From project JDave, under directory /jdave-junit3/src/test/jdave/junit3/.

Source file: ResultAdapterTest.java

  31 
vote

@Override protected void setUp() throws Exception {
  result=new TestResult();
  test=new TestCase("test"){
  }
;
  adapter=new JDaveSuite.ResultAdapter(test,result);
  method=ResultAdapterTest.class.getDeclaredMethod("setUp");
}
 

Example 8

From project k-9, under directory /tests/src/com/zutubi/android/junitreport/.

Source file: JUnitReportListener.java

  31 
vote

@Override public void startTest(Test test){
  try {
    if (test instanceof TestCase) {
      TestCase testCase=(TestCase)test;
      checkForNewSuite(testCase);
      mSerializer.startTag("",TAG_CASE);
      mSerializer.attribute("",ATTRIBUTE_CLASS,mCurrentSuite);
      mSerializer.attribute("",ATTRIBUTE_NAME,testCase.getName());
      mTimeAlreadyWritten=false;
      mTestStartTime=System.currentTimeMillis();
    }
  }
 catch (  IOException e) {
    Log.e(LOG_TAG,safeMessage(e));
  }
}
 

Example 9

From project Kairos, under directory /src/plugin/parse-mspowerpoint/src/test/org/apache/nutch/parse/mspowerpoint/.

Source file: AllTests.java

  31 
vote

/** 
 * @return Test for the PowerPoint plugin
 */
public static Test suite(){
  final TestSuite suite=new TestSuite("Test for org.apache.nutch.parse.mspowerpoint");
  System.out.println("Testing with ppt-files of dir: " + SAMPLE_DIR);
  final File sampleDir=new File(SAMPLE_DIR);
  final FileExtensionFilter pptFilter=new FileExtensionFilter(".ppt");
  final String[] pptFiles=sampleDir.list(pptFilter);
  if (pptFiles == null) {
    throw new IllegalArgumentException(SAMPLE_DIR + " does not contain any files: " + pptFilter);
  }
  TestSuite suiteAllFiles;
  for (int i=0; i < pptFiles.length; i++) {
    suiteAllFiles=new TestSuite("Testing file [" + pptFiles[i] + "]");
    TestCase test=new TestMSPowerPointParser(new File(pptFiles[i]));
    test.setName("testContent");
    suiteAllFiles.addTest(test);
    TestCase test2=new TestMSPowerPointParser(new File(pptFiles[i]));
    test2.setName("testMeta");
    suiteAllFiles.addTest(test2);
    suite.addTest(suiteAllFiles);
  }
  return suite;
}
 

Example 10

From project agile, under directory /agile-storage/src/test/java/org/headsupdev/agile/storage/issues/.

Source file: DurationTest.java

  29 
vote

public void testHoursToString(){
  Duration hours=new Duration(5);
  TestCase.assertEquals("Wrong rendering for hours duration","5h",hours.toString());
  hours=new Duration(5,Duration.UNIT_HOURS);
  TestCase.assertEquals("Wrong rendering for hours duration","5h",hours.toString());
}
 

Example 11

From project ardverk-commons, under directory /src/test/java/org/ardverk/collection/.

Source file: ZipperTest.java

  29 
vote

@Test public void add(){
  Zipper<String> list=Zipper.create();
  list=list.add("Hello").add("World");
  TestCase.assertFalse(list.isEmpty());
  TestCase.assertEquals(2,list.size());
  TestCase.assertTrue(list.contains("Hello"));
  TestCase.assertTrue(list.contains("World"));
  TestCase.assertFalse(list.contains("Foo Bar"));
}
 

Example 12

From project ardverk-dht, under directory /components/core/src/test/java/org/ardverk/dht/codec/bencode/.

Source file: BencodeMessageCodecTest.java

  29 
vote

@Test public void encodeDecode() throws IOException {
  BencodeMessageCodec codec=new BencodeMessageCodec();
  MessageId messageId=MessageId.createRandom(20);
  KUID contactId=KUID.createRandom(20);
  Contact contact=new DefaultContact(Type.SOLICITED,contactId,0,false,new InetSocketAddress("localhost",6666));
  SocketAddress address=new InetSocketAddress("localhost",6666);
  PingRequest request=new DefaultPingRequest(messageId,contact,address);
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Encoder encoder=codec.createEncoder(baos);
  encoder.write(request);
  encoder.close();
  ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
  Decoder decoder=codec.createDecoder(address,bais);
  Message message=decoder.read();
  decoder.close();
  TestCase.assertTrue(message instanceof PingRequest);
}
 

Example 13

From project book, under directory /src/test/java/com/tamingtext/classifier/bayes/.

Source file: ExtractTrainingDataTest.java

  29 
vote

@Test public void testExtract() throws Exception {
  assertU("Add a doc to be classified",adoc("id","1","category","scifi","details","Star Wars: A New Hope"));
  assertU("Add a doc to be classified",adoc("id","2","category","scifi","details","Star Wars: The Empire Strikes Back"));
  assertU("Add a doc to be classified",adoc("id","3","category","scifi","details","Star Wars: The Revenge of the Jedi"));
  assertU("Add a doc to be classified",adoc("id","4","category","fantasy","details","Lord of the Rings: Fellowship of the Ring"));
  assertU("Add a doc to be classified",adoc("id","5","category","fantasy","details","Lord of the Rings: The Two Towers"));
  assertU("Add a doc to be classified",adoc("id","6","category","fantasy","details","Lord of the Rings: Return of the King"));
  assertU(commit());
  File outputDir=new File(baseDir,"extract");
  File indexDir=new File(dataDir,"index");
  File categoryFile=new File("src/test/resources/solr/conf/categories.txt");
  String[] extractArgs={"--dir",indexDir.getAbsolutePath(),"--categories",categoryFile.getAbsolutePath(),"--output",outputDir.getAbsolutePath(),"--category-fields","category","--text-fields","details","--use-term-vectors"};
  ExtractTrainingData.main(extractArgs);
  File[] files=outputDir.listFiles();
  Map<String,File> names=new HashMap<String,File>();
  for (  File f : files) {
    names.put(f.getName(),f);
  }
  TestCase.assertEquals(2,files.length);
  TestCase.assertTrue("File list contains scifi",names.containsKey("scifi"));
  TestCase.assertTrue("File list contains fantasy",names.containsKey("fantasy"));
  String scifiContent=readFile(names.get("scifi"));
  TestCase.assertTrue("Sci-fi file has proper label",scifiContent.startsWith("scifi\t"));
  TestCase.assertTrue("Sci-fi file contents",scifiContent.contains("star"));
  TestCase.assertTrue("Sci-fi file contents",scifiContent.contains("jedi"));
  String fantasyContent=readFile(names.get("fantasy"));
  TestCase.assertTrue("Fantasy file has proper label",fantasyContent.startsWith("fantasy\t"));
  TestCase.assertTrue("Fantasy file contents",fantasyContent.contains("lord"));
  TestCase.assertTrue("Fantasy file contents",fantasyContent.contains("tower"));
  File modelDir=new File(baseDir,"model");
  String[] trainArgs={"-i",outputDir.getAbsolutePath(),"-o",modelDir.getAbsolutePath(),"-ng","1","-type","bayes","-source","hdfs"};
  TrainClassifier.main(trainArgs);
  String[] testArgs={"-d",outputDir.getAbsolutePath(),"-m",modelDir.getAbsolutePath(),"-ng","1","-type","bayes","-source","hdfs"};
  TestClassifier.main(testArgs);
}
 

Example 14

From project ceres, under directory /ceres-ui/src/test/java/com/bc/ceres/swing/binding/.

Source file: ValueEditorRegistryTest.java

  29 
vote

public void testFindValueEditor_UnknownEditor() throws Exception {
  PropertyDescriptor descriptor=new PropertyDescriptor("test",TestCase.class);
  PropertyEditor propertyEditor=editorRegistry.findPropertyEditor(descriptor);
  assertNotNull(propertyEditor);
  assertSame(TextFieldEditor.class,propertyEditor.getClass());
}
 

Example 15

From project core_1, under directory /runtime/src/test/java/org/switchyard/.

Source file: MockHandler.java

  29 
vote

/** 
 * Wait for a number of messages.
 * @param eventQueue event queue
 * @param numMessages number of messages
 */
private void waitFor(final LinkedBlockingQueue<Exchange> eventQueue,final int numMessages){
  long start=System.currentTimeMillis();
  while (System.currentTimeMillis() < start + _waitTimeout) {
    if (eventQueue.size() >= numMessages) {
      return;
    }
    sleep();
  }
  TestCase.fail("Timed out waiting on event queue length to be " + numMessages + " or greater.");
}
 

Example 16

From project culvert, under directory /hive-culvert-handler/src/test/java/com/bah/culvert/.

Source file: CulvertHiveIT.java

  29 
vote

@Test public void testHiveScript() throws Throwable {
  util.addFile(scriptLocation);
  util.clearTestSideEffects();
  util.cliInit(scriptLocation);
  int parseRes=util.executeClient(scriptName);
  TestCase.assertEquals(0,parseRes);
  int verifyRes=util.checkCliDriverResults(scriptName);
  TestCase.assertEquals(0,verifyRes);
}
 

Example 17

From project des, under directory /daemon/lib/apache-log4j-1.2.16/tests/src/java/org/apache/log4j/util/.

Source file: SerializationTestHelper.java

  29 
vote

/** 
 * Asserts the serialized form of an object.
 * @param witness file name of expected serialization.
 * @param actual byte array of actual serialization.
 * @param skip positions to skip comparison.
 * @param endCompare position to stop comparison.
 * @throws IOException thrown on IO or serialization exception.
 */
public static void assertStreamEquals(final String witness,final byte[] actual,final int[] skip,final int endCompare) throws IOException {
  File witnessFile=new File(witness);
  if (witnessFile.exists()) {
    int skipIndex=0;
    byte[] expected=new byte[actual.length];
    FileInputStream is=new FileInputStream(witnessFile);
    int bytesRead=is.read(expected);
    is.close();
    if (bytesRead < endCompare) {
      TestCase.assertEquals(bytesRead,actual.length);
    }
    int endScan=actual.length;
    if (endScan > endCompare) {
      endScan=endCompare;
    }
    for (int i=0; i < endScan; i++) {
      if ((skipIndex < skip.length) && (skip[skipIndex] == i)) {
        skipIndex++;
      }
 else {
        if (expected[i] != actual[i]) {
          TestCase.assertEquals("Difference at offset " + i,expected[i],actual[i]);
        }
      }
    }
  }
 else {
    FileOutputStream os=new FileOutputStream(witnessFile);
    os.write(actual);
    os.close();
    TestCase.fail("Writing witness file " + witness);
  }
}
 

Example 18

From project discovery, under directory /src/test/java/com/tacitknowledge/util/discovery/.

Source file: ClassDiscoveryUtilTest.java

  29 
vote

/** 
 * Basic test of <code>ClassDiscoveryUtil.getResources(String, String)</code> when the resource lives in an archive.
 */
public void testGetRegexResourcesInArchive(){
  String dir=TestCase.class.getPackage().getName().replace('.',File.separatorChar);
  String regex="^TestCase.+";
  String[] names=ClassDiscoveryUtil.getResources(dir,regex);
  assertNotNull(names);
  assertTrue(names.length >= 1);
  assertEquals(dir + File.separator + "TestCase.class",names[0]);
}
 

Example 19

From project eclipse.platform.runtime, under directory /tests/org.eclipse.core.expressions.tests/src/org/eclipse/core/internal/expressions/tests/.

Source file: ExpressionTestsPluginUnloading.java

  29 
vote

public static Test suite(){
  TestSuite suite=new TestSuite(ExpressionTestsPluginUnloading.class);
  ArrayList tests=Collections.list(suite.tests());
  Collections.sort(tests,new Comparator(){
    public int compare(    Object o1,    Object o2){
      return ((TestCase)o1).getName().compareTo(((TestCase)o2).getName());
    }
  }
);
  TestSuite result=new TestSuite();
  for (Iterator iter=tests.iterator(); iter.hasNext(); ) {
    result.addTest((TestCase)iter.next());
  }
  return result;
}
 

Example 20

From project encog-java-core, under directory /src/test/java/org/encog/bot/browse/.

Source file: TestWebPageData.java

  29 
vote

@Test public void testSimple() throws Throwable {
  LoadWebPage load=new LoadWebPage(null);
  WebPage page=load.load("a<b>b</b>c");
  TestCase.assertEquals(5,page.getData().size());
  TextDataUnit textDU;
  TagDataUnit tagDU;
  textDU=(TextDataUnit)page.getDataUnit(0);
  Assert.assertEquals("a",textDU.toString());
  tagDU=(TagDataUnit)page.getDataUnit(1);
  Assert.assertEquals("b",tagDU.getTag().getName());
  Assert.assertEquals("<b>",tagDU.toString());
  Assert.assertEquals(Tag.Type.BEGIN,tagDU.getTag().getType());
  textDU=(TextDataUnit)page.getDataUnit(2);
  Assert.assertEquals("b",textDU.toString());
  tagDU=(TagDataUnit)page.getDataUnit(3);
  Assert.assertEquals("b",tagDU.getTag().getName());
  Assert.assertEquals(Tag.Type.END,tagDU.getTag().getType());
  textDU=(TextDataUnit)page.getDataUnit(4);
  Assert.assertEquals("c",textDU.toString());
}
 

Example 21

From project fitnesse, under directory /src/fit/decorator/util/.

Source file: TestCaseHelper.java

  29 
vote

public static void assertCounts(Counts expected,Counts actual){
  TestCase.assertEquals(expected.wrong,actual.wrong);
  TestCase.assertEquals(expected.exceptions,actual.exceptions);
  TestCase.assertEquals(expected.ignores,actual.ignores);
  TestCase.assertEquals(expected.right,actual.right);
}
 

Example 22

From project floodlight, under directory /src/test/java/net/floodlightcontroller/core/util/.

Source file: AppCookieTest.java

  29 
vote

public void testAppCookie(){
  int appID=12;
  int user=12345;
  long cookie=AppCookie.makeCookie(appID,user);
  TestCase.assertEquals(appID,AppCookie.extractApp(cookie));
  TestCase.assertEquals(user,AppCookie.extractUser(cookie));
  cookie=AppCookie.makeCookie(appID + 0x10000,user);
  TestCase.assertEquals(appID,AppCookie.extractApp(cookie));
  TestCase.assertEquals(user,AppCookie.extractUser(cookie));
}
 

Example 23

From project flume, under directory /flume-ng-core/src/test/java/org/apache/flume/source/.

Source file: TestStressSource.java

  29 
vote

@Test public void testBatchEvents() throws InterruptedException, EventDeliveryException {
  StressSource source=new StressSource();
  source.setChannelProcessor(mockProcessor);
  Context context=new Context();
  context.put("maxTotalEvents","35");
  context.put("batchSize","10");
  source.configure(context);
  for (int i=0; i < 50; i++) {
    if (source.process() == Status.BACKOFF) {
      TestCase.assertTrue("Source should have sent all events in 4 batches",i == 4);
      break;
    }
    if (i < 3) {
      verify(mockProcessor,times(i + 1)).processEventBatch(getLastProcessedEventList(source));
    }
 else {
      verify(mockProcessor,times(1)).processEventBatch(getLastProcessedEventList(source));
    }
  }
  long successfulEvents=getCounterGroup(source).get("events.successful");
  TestCase.assertTrue("Number of successful events should be 35 but was " + successfulEvents,successfulEvents == 35);
  long failedEvents=getCounterGroup(source).get("events.failed");
  TestCase.assertTrue("Number of failure events should be 0 but was " + failedEvents,failedEvents == 0);
}
 

Example 24

From project frameworks_opt, under directory /vcard/tests/src/com/android/vcard/tests/testutils/.

Source file: ExportTestProvider.java

  29 
vote

/** 
 * <p> An old method which had existed but was removed from ContentResolver. </p> <p> We still keep using this method since we don't have a propeer way to know which value in the ContentValue corresponds to the entry in Contacts database. </p>
 */
public EntityIterator queryEntities(Uri uri,String selection,String[] selectionArgs,String sortOrder){
  TestCase.assertTrue(uri != null);
  TestCase.assertTrue(ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()));
  final String authority=uri.getAuthority();
  TestCase.assertTrue(RawContacts.CONTENT_URI.getAuthority().equals(authority));
  TestCase.assertTrue((Data.CONTACT_ID + "=?").equals(selection));
  TestCase.assertEquals(1,selectionArgs.length);
  final int id=Integer.parseInt(selectionArgs[0]);
  TestCase.assertTrue(id >= 0);
  TestCase.assertTrue(id < mContactEntryList.size());
  return new MockEntityIterator(mContactEntryList.get(id).getList());
}
 

Example 25

From project heritrix3, under directory /commons/src/main/java/org/archive/util/.

Source file: TestUtils.java

  29 
vote

public static void testSerialization(Object proc) throws Exception {
  byte[] first=serialize(proc);
  ByteArrayInputStream binp=new ByteArrayInputStream(first);
  ObjectInputStream oinp=new ObjectInputStream(binp);
  Object o=oinp.readObject();
  oinp.close();
  TestCase.assertEquals(proc.getClass(),o.getClass());
  byte[] second=serialize(o);
  TestCase.assertTrue(Arrays.equals(first,second));
}
 

Example 26

From project hornetq-version-tests, under directory /src/test/java/org/hornetq/jms/.

Source file: JoramAggregationTest.java

  29 
vote

/** 
 * Create a dummy test renaming its content
 * @param test
 * @return
 */
private Test createDummyTest(Test test){
  Test dummyTest=(Test)hashTests.get(test);
  if (dummyTest == null) {
    if (test instanceof TestCase) {
      dummyTest=new DummyTestCase(this.getName() + ":" + ((TestCase)test).getName());
    }
 else     if (test instanceof TestSuite) {
      dummyTest=new DummyTestCase(this.getName() + ":" + ((TestCase)test).getName());
    }
 else {
      dummyTest=new DummyTestCase(test.getClass().getName());
    }
    hashTests.put(test,dummyTest);
  }
  return dummyTest;
}
 

Example 27

From project jentrata-msh, under directory /Commons/src/test/java/hk/hku/cecid/piazza/commons/dao/.

Source file: AbstractDVOTest.java

  29 
vote

public void testInt() throws Exception {
  int i=12345678;
  dvo.setInt("int1",i);
  TestCase.assertEquals(i,dvo.getInt("int1"));
  dvo.getData().put("int2",new Integer(i));
  TestCase.assertEquals(i,dvo.getInt("int2"));
  dvo.getData().put("int3",new Integer(i));
  TestCase.assertEquals(Integer.toString(i),dvo.getString("int3"));
  dvo.getData().put("int4",new BigDecimal(i));
  TestCase.assertEquals(i,dvo.getInt("int4"));
  TestCase.assertEquals(Integer.MIN_VALUE,dvo.getInt("int5"));
}
 

Example 28

From project JSimpleTracker, under directory /libs/apache-log4j-1.2.16/apache-log4j-1.2.16/tests/src/java/org/apache/log4j/util/.

Source file: SerializationTestHelper.java

  29 
vote

/** 
 * Asserts the serialized form of an object.
 * @param witness file name of expected serialization.
 * @param actual byte array of actual serialization.
 * @param skip positions to skip comparison.
 * @param endCompare position to stop comparison.
 * @throws IOException thrown on IO or serialization exception.
 */
public static void assertStreamEquals(final String witness,final byte[] actual,final int[] skip,final int endCompare) throws IOException {
  File witnessFile=new File(witness);
  if (witnessFile.exists()) {
    int skipIndex=0;
    byte[] expected=new byte[actual.length];
    FileInputStream is=new FileInputStream(witnessFile);
    int bytesRead=is.read(expected);
    is.close();
    if (bytesRead < endCompare) {
      TestCase.assertEquals(bytesRead,actual.length);
    }
    int endScan=actual.length;
    if (endScan > endCompare) {
      endScan=endCompare;
    }
    for (int i=0; i < endScan; i++) {
      if ((skipIndex < skip.length) && (skip[skipIndex] == i)) {
        skipIndex++;
      }
 else {
        if (expected[i] != actual[i]) {
          TestCase.assertEquals("Difference at offset " + i,expected[i],actual[i]);
        }
      }
    }
  }
 else {
    FileOutputStream os=new FileOutputStream(witnessFile);
    os.write(actual);
    os.close();
    TestCase.fail("Writing witness file " + witness);
  }
}
 

Example 29

From project kawala, under directory /kawala-testing/src/main/java/com/kaching/platform/testing/.

Source file: TestSuiteBuilder.java

  29 
vote

private void addTestsInDirectory(File directory,TestFilter filter){
  for (  File file : directory.listFiles()) {
    if (file.isDirectory()) {
      addTestsInDirectory(file,filter);
    }
 else     if (file.getName().endsWith(".java")) {
      Class<?> clazz=forName(file);
      if (filter.shouldIncludeTest(clazz)) {
        if (TestCase.class.isAssignableFrom(clazz) && clazz.getAnnotation(Ignore.class) == null) {
          testSuite.addTestSuite(castToTestCase(clazz));
        }
 else         if (hasTests(clazz) && filter.shouldIncludeTest(clazz)) {
          JUnit4TestAdapter test=new JUnit4TestAdapter(clazz);
          testSuite.addTest(test);
        }
      }
    }
  }
}
 

Example 30

From project log4j, under directory /tests/src/java/org/apache/log4j/util/.

Source file: SerializationTestHelper.java

  29 
vote

/** 
 * Asserts the serialized form of an object.
 * @param witness file name of expected serialization.
 * @param actual byte array of actual serialization.
 * @param skip positions to skip comparison.
 * @param endCompare position to stop comparison.
 * @throws IOException thrown on IO or serialization exception.
 */
public static void assertStreamEquals(final String witness,final byte[] actual,final int[] skip,final int endCompare) throws IOException {
  File witnessFile=new File(witness);
  if (witnessFile.exists()) {
    int skipIndex=0;
    byte[] expected=new byte[actual.length];
    FileInputStream is=new FileInputStream(witnessFile);
    int bytesRead=is.read(expected);
    is.close();
    if (bytesRead < endCompare) {
      TestCase.assertEquals(bytesRead,actual.length);
    }
    int endScan=actual.length;
    if (endScan > endCompare) {
      endScan=endCompare;
    }
    for (int i=0; i < endScan; i++) {
      if ((skipIndex < skip.length) && (skip[skipIndex] == i)) {
        skipIndex++;
      }
 else {
        if (expected[i] != actual[i]) {
          TestCase.assertEquals("Difference at offset " + i,expected[i],actual[i]);
        }
      }
    }
  }
 else {
    FileOutputStream os=new FileOutputStream(witnessFile);
    os.write(actual);
    os.close();
    TestCase.fail("Writing witness file " + witness);
  }
}