1 package org.displaytag.test; 2 3 import junit.framework.Assert; 4 5 import org.apache.commons.lang.ArrayUtils; 6 import org.apache.commons.lang.StringUtils; 7 8 9 /** 10 * Assert class used to compare URLs. 11 * @author Fabrizio Giustina 12 * @version $Revision: 729 $ ($Author: fgiust $) 13 */ 14 public final class URLAssert 15 { 16 17 /** 18 * Don't instantiate. 19 */ 20 private URLAssert() 21 { 22 // unused 23 } 24 25 /** 26 * utility method for comparing two URLs. 27 * @param expectedUrl expected URL 28 * @param generatedUrl generated URL 29 */ 30 public static void assertEquals(String expectedUrl, String generatedUrl) 31 { 32 // hack for missing base url 33 if (expectedUrl.startsWith("?")) 34 { 35 expectedUrl = "[empty]" + expectedUrl; 36 } 37 if (generatedUrl.startsWith("?")) 38 { 39 generatedUrl = "[empty]" + generatedUrl; 40 } 41 42 // if urls contains parameters they could be written in different order 43 String[] generatedSplit = StringUtils.split(generatedUrl, "?#"); 44 String[] expectedSplit = StringUtils.split(expectedUrl, "?#"); 45 46 Assert.assertEquals( 47 "Different number of tokens (base, parameters, anchor) in link.", 48 generatedSplit.length, 49 expectedSplit.length); 50 51 // same base url 52 Assert.assertEquals("Wrong base url", generatedSplit[0], expectedSplit[0]); 53 54 // same anchor # 55 if (generatedSplit.length > 2) 56 { 57 Assert.assertEquals("Anchor is different", generatedSplit[2], expectedSplit[2]); 58 } 59 else if (generatedSplit.length > 1 && (generatedUrl.indexOf("?") == -1)) 60 { 61 // url without parameters 62 Assert.assertEquals("Anchor is different", generatedSplit[1], expectedSplit[1]); 63 return; 64 } 65 66 // same parameters 67 if (generatedSplit.length > 1) 68 { 69 // compare parameters 70 String[] generatedParameters = StringUtils.split(StringUtils.replace(generatedSplit[1], "&", "&"), '&'); 71 String[] expectedParameters = StringUtils.split(StringUtils.replace(expectedSplit[1], "&", "&"), '&'); 72 73 Assert.assertEquals( 74 "Compared urls have different number of parameters", 75 expectedParameters.length, 76 generatedParameters.length); 77 78 for (int j = 0; j < expectedParameters.length; j++) 79 { 80 // assuming url?param == url?param= 81 String singleParam = expectedParameters[j]; 82 if (singleParam.indexOf("=") == -1) 83 { 84 singleParam += "="; 85 } 86 Assert.assertTrue( 87 "Expected parameter " + singleParam + " could not be found in generated URL", 88 ArrayUtils.contains(generatedParameters, singleParam)); 89 } 90 } 91 } 92 }