1 21 22 package org.apache.commons.validator; 23 24 import junit.framework.TestCase; 25 26 29 public class CreditCardValidatorTest extends TestCase { 30 31 private static final String VALID_VISA = "4417123456789113"; 32 private static final String VALID_SHORT_VISA = "4222222222222"; 33 private static final String VALID_AMEX = "378282246310005"; 34 private static final String VALID_MASTERCARD = "5105105105105100"; 35 private static final String VALID_DISCOVER = "6011000990139424"; 36 private static final String VALID_DINERS = "30569309025904"; 37 38 41 public CreditCardValidatorTest(String name) { 42 super(name); 43 } 44 45 public void testIsValid() { 46 CreditCardValidator ccv = new CreditCardValidator(); 47 48 assertFalse(ccv.isValid(null)); 49 assertFalse(ccv.isValid("")); 50 assertFalse(ccv.isValid("123456789012")); assertFalse(ccv.isValid("12345678901234567890")); assertFalse(ccv.isValid("4417123456789112")); 53 assertFalse(ccv.isValid("4417q23456w89113")); 54 assertTrue(ccv.isValid(VALID_VISA)); 55 assertTrue(ccv.isValid(VALID_SHORT_VISA)); 56 assertTrue(ccv.isValid(VALID_AMEX)); 57 assertTrue(ccv.isValid(VALID_MASTERCARD)); 58 assertTrue(ccv.isValid(VALID_DISCOVER)); 59 60 ccv = new CreditCardValidator(CreditCardValidator.AMEX); 62 assertFalse(ccv.isValid("4417123456789113")); 63 } 64 65 public void testAddAllowedCardType() { 66 CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.NONE); 67 assertFalse(ccv.isValid(VALID_VISA)); 69 assertFalse(ccv.isValid(VALID_AMEX)); 70 assertFalse(ccv.isValid(VALID_MASTERCARD)); 71 assertFalse(ccv.isValid(VALID_DISCOVER)); 72 73 ccv.addAllowedCardType(new DinersClub()); 75 assertTrue(ccv.isValid(VALID_DINERS)); 76 } 77 78 81 private class DinersClub implements CreditCardValidator.CreditCardType { 82 private static final String PREFIX = "300,301,302,303,304,305,"; 83 public boolean matches(String card) { 84 String prefix = card.substring(0, 3) + ","; 85 return ((PREFIX.indexOf(prefix) != -1) && (card.length() == 14)); 86 } 87 } 88 89 } 90 | Popular Tags |