I have an entity in Domain Model. This entity has ChangeStatus(StatusesEnum newStatus) method. StatusesEnum has more then 10 members. They can be changed only in correct order, for example StatusesEnum.First can be changed to Second and Third, Third can be changed to Fourth only, Fourth can be changed to Fifth and Seventh etc.
ChangeStatus method is throwing exception for wrong transitions. I don't think that testing all cases is right (maybe I开发者_JS百科'm wrong :)), however how can I write test for checking right transitions order.
> how can I write test for checking right transitions order.
If you are using NUnit 2.5 or later you can use Parameterized Tests
[Test, Sequential]
public void MyTest(
[Values(State1,State2,State99)] StatusesEnum initialState,
[Values(State2,State3,State1)] StatusesEnum nextState,
[Values(true, true, false)] bool expectedOutcome
)
{
Entity entity = new Entity(initialState);
if (expectedOutcome)
entity.ChangeStatus(nextState); // this should be ok
else {
try {
entity.ChangeStatus(nextState);
// this should throw
Assert.Fail("Missing expected Exception");
} catch (IllegaleStateTransitionException ex) {
// every thing is ok
}
}
...
}
However if i were you i would create a non-throwing decision-function
IsValidTransition(StatusesEnum oldState, StatusesEnum newState)
that is to be used in you statelogic and is tested in unittest so there is no more need to test the exception logic
How thorough you want to be is up to you. I'd have tests for each of the correct transitions, e.g.
[Test]
public void ChangeStatus_FirstToSecond_Succeeds()
{
Entity entity = new Entity(StatusEnum.First);
entity.ChangeStatus(StatusEnum.Second);
Assert.That(entity.Status, Is.EqualTo(StatusEnum.Second);
}
And a test for one invalid transition per input state:
[Test]
[ExpectedException(typeof(StatusChangeException))]
public void ChangeStatus_FirstToTenth_ThrowsException()
{
Entity entity = new Entity(StatusEnum.First);
entity.ChangeStatus(StatusEnum.Tenth);
}
精彩评论