2009年8月31日月曜日

JUnit assertThat用のBetweenクラスを作ってみた

JUnitのassertThatで有効範囲を指定してテストを行うためのクラスを作った

使い方は


Assert.assertThat(2,Between.between(1,4));



みたいな感じ


以下コード



import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
/**
* Comparableなものをが特定の範囲内の値であるかどうかを判定する
* @author takeshita
*
*/
public class Between extends BaseMatcher<Comparable>{

/**
* lower <= value <= upper
* @param lowerLimit
* @param upperLimit
* @return
*/
public static Between between(Comparable lowerLimit ,Comparable upperLimit)
{
return between_UE_LE(lowerLimit,upperLimit);
}
/**
* lower < value < upper
* @param lowerLimit
* @param upperLimit
* @return
*/
public static Between between_UT_LT(Comparable lowerLimit ,Comparable upperLimit)
{
return new Between(lowerLimit,upperLimit,0,0);
}
/**
* lower <= value < upper
* @param lowerLimit
* @param upperLimit
* @return
*/
public static Between between_UE_LT(Comparable lowerLimit ,Comparable upperLimit)
{
return new Between(lowerLimit,upperLimit,1,0);
}
/**
* lower < value <= upper
* @param lowerLimit
* @param upperLimit
* @return
*/
public static Between between_UT_LE(Comparable lowerLimit ,Comparable upperLimit)
{
return new Between(lowerLimit,upperLimit,0,-1);
}

/**
* lower <= value <= upper
* @param lowerLimit
* @param upperLimit
* @return
*/
public static Between between_UE_LE(Comparable lowerLimit ,Comparable upperLimit)
{
return new Between(lowerLimit,upperLimit,1,-1);
}


Comparable lowerLimit ,upperLimit;
int lowerThreshold = 0,upperThreshold = 0;
private Between(Comparable lowerLimit ,Comparable upperLimit,
int lowerThreshold,int upperThreshold)
{
this.lowerLimit = lowerLimit;
this.upperLimit = upperLimit;
this.lowerThreshold = lowerThreshold;
this.upperThreshold = upperThreshold;
}



@Override
public boolean matches(Object obj) {
return lowerLimit.compareTo(obj) < lowerThreshold &&
upperLimit.compareTo(obj) > upperThreshold;
}



@Override
public void describeTo(Description desc) {
desc.appendText(
lowerLimit.toString() +
(lowerThreshold == 0 ? " < value " : " <= value ") +
(upperThreshold == 0 ? "< " : "<= ") +
upperLimit.toString());

}
}

1 件のコメント:

  1. おはようございます。

    あると便利な機能ですね!

    返信削除