I have a java program which will check for start date and end date of each item. Each Item must have their own specific start date and end date range. And this system will promp
Here is simple unit test of a possible implementation using Joda-Time and Guava's Range.
import com.google.common.collect.Lists;
import com.google.common.collect.Range;
import org.joda.time.LocalDate;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class ItemDateRangeTest {
static class Item {
private final String id;
private final LocalDate startDate;
private final LocalDate endDate;
public Item(String id, LocalDate startDate, LocalDate endDate) {
this.id = id;
this.startDate = startDate;
this.endDate = endDate;
}
public String getId() {
return id;
}
public LocalDate getStartDate() {
return startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public Range getRange() {
// Closed range includes the lower and upper bounds
return Range.closed(startDate, endDate);
}
}
static class ItemStore {
private final List- items = Lists.newArrayList();
public void add(Item newItem) throws IllegalArgumentException{
for (Item item : items) {
if (item.getRange().isConnected(newItem.getRange())) {
throw new IllegalArgumentException("error: date range overlap!");
}
}
items.add(newItem);
}
public List
- getItems() {
return items;
}
}
@Test()
public void testItemDateRangeNoOverlap() {
final ItemStore itemStore = new ItemStore();
Item itemA = new Item("11A", new LocalDate(2014, 8, 1), new LocalDate(2014, 9, 1));
Item itemB = new Item("11B", new LocalDate(2014, 9, 2), new LocalDate(2014, 9, 30));
itemStore.add(itemA);
itemStore.add(itemB);
assertEquals(itemStore.getItems().get(0), itemA);
assertEquals(itemStore.getItems().get(1), itemB);
}
@Test(expected = IllegalArgumentException.class)
public void testItemDateRangeWithOverlap() {
final ItemStore itemStore = new ItemStore();
itemStore.add(new Item("11A", new LocalDate(2014,8,1), new LocalDate(2014,9,1)));
itemStore.add(new Item("11B", new LocalDate(2014,9,2), new LocalDate(2014,9,30)));
itemStore.add(new Item("11C", new LocalDate(2014,8,18), new LocalDate(2014,8,30)));
}
}