I have an extension method that calculates due date based on date period type. The method looks like this:
public static DateTime CalculateDueDate(this DateTime date, OffsetType offsetType, int offset)
{
switch (offsetType)
{
case OffsetType.Days:
return date.AddDays(offset);
case OffsetType.Weeks:
return date.AddWeeks(offset);
case OffsetType.Months:
return date.AddMonths(offset);
default:
throw new ArgumentOutOfRangeException("offsetType", offsetType, null);
}
}
where OffsetType enum has these possible values:
public enum OffsetType
{
Months = 1,
Weeks = 2,
Days = 3
}
How can I make sure that ArgumentOutOfRangeException
is thrown when OffsetType
enum
is not provided (or provided with invalid value)? Do I even need to worry about unit testing that exception if OffsetType
parameter is not null
?
UPDATE:
I wish I could vote for multiple answers. I decided to use out-of-range value suggested by Lee and dasblinkenlight. Here is my fins unit test:
[Test]
public void CalculateDueDate_Throw_Exception_Test()
{
var date = DateTime.Now;
var period = 3;
var offsetType = (OffsetType) (-1);
Assert.Throws<ArgumentOutOfRangeException>(() => date.CalculateDueDate(offsetType, period));
}
Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not.
Yes - any such instance methods would be inaccessible. Further, I can't think of much useful to do with an empty enum.
But your test case will pass & you will see a Junit green bar once you turn on mock maker feature as mentioned above. This way you can mock Java enum or a final class with Junit & Mockito. You don't need any other additional framework.
An enum value cannot be null. It is a value type like an int. To avoid the "cannot convert null" error, use a special None constant as the first enum item.
You can just cast an out-of-range value to the enum type:
Assert.Throws<ArgumentOutOfRangeException>(() => {
CalculateDueDate(date, (OffsetType)(-1), offset);
});
Which values you can use depend on the underlying type of the enum.
You can construct an illegal value by explicitly casting an out-of-range int
to OffsetType
, for example
OffsetType t = (OffsetType)5;
Now you can call CalculateDueDate
, pass it the illegal value constructed for the unit test, and assert that an exception of type ArgumentOutOfRangeException
is thrown.
Note: Although it is redundant in situations when you perform an exhaustive switch
covering all enum
cases, in situations when you cover some valid cases with a default
branch you should check for invalid values using Enum.IsDefined(typeof(OffsetType), t)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With