New constructor and "canIncrement" method.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1167371 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gilles Sadowski 2011-09-09 21:58:37 +00:00
parent 2342db442a
commit 8f09fa850a
2 changed files with 75 additions and 1 deletions

View File

@ -35,8 +35,29 @@ public class Incrementor {
*/
private int count;
/**
* Default constructor.
* For the new instance to be useful, the maximal count must be set
* by calling {@link #setMaximalCount(int) setMaximalCount}.
*/
public Incrementor() {
this(0);
}
/**
* Defines a maximal count.
*
* @param max Maximal count.
*/
public Incrementor(int max) {
maximalCount = max;
count = 0;
}
/**
* Set the upper limit for the counter.
* This does not automatically reset the current count to zero (see
* {@link #resetCount()}).
*
* @param max Upper limit of the counter.
*/
@ -62,6 +83,17 @@ public class Incrementor {
return count;
}
/**
* Check whether a single increment is allowed.
*
* @return {@code false} if the next call to {@link #incrementCount(int)
* incrementCount} will trigger a {@code MaxCountExceededException},
* {@code true} otherwise.
*/
public boolean canIncrement() {
return count < maximalCount;
}
/**
* Perform multiple increments.
* See the other {@link #incrementCount() incrementCount} method).

View File

@ -21,6 +21,48 @@ import org.junit.Test;
* Test for {@link Incrementor}.
*/
public class IncrementorTest {
@Test
public void testConstructor1() {
final Incrementor i = new Incrementor();
Assert.assertEquals(0, i.getMaximalCount());
Assert.assertEquals(0, i.getCount());
}
@Test
public void testConstructor2() {
final Incrementor i = new Incrementor(10);
Assert.assertEquals(10, i.getMaximalCount());
Assert.assertEquals(0, i.getCount());
}
@Test
public void testCanIncrement1() {
final Incrementor i = new Incrementor(3);
Assert.assertTrue(i.canIncrement());
i.incrementCount();
Assert.assertTrue(i.canIncrement());
i.incrementCount();
Assert.assertTrue(i.canIncrement());
i.incrementCount();
Assert.assertFalse(i.canIncrement());
}
@Test
public void testCanIncrement2() {
final Incrementor i = new Incrementor(3);
while (i.canIncrement()) {
i.incrementCount();
}
// Must keep try/catch because the exception must be generated here,
// and not in the previous loop.
try {
i.incrementCount();
Assert.fail("MaxCountExceededException expected");
} catch (MaxCountExceededException e) {
// Expected.
}
}
@Test
public void testAccessor() {
@ -43,7 +85,7 @@ public class IncrementorTest {
Assert.assertEquals(3, i.getCount());
}
@Test(expected = MaxCountExceededException.class)
@Test(expected=MaxCountExceededException.class)
public void testAboveMaxCount() {
final Incrementor i = new Incrementor();