In a large application, I have a lot of methods with input arguments that each argument is a model with nested models (as you see in the image).
You see that I have written some conditional codes and TestCases in this unit test to check each case that one of the child properties is invalid.
In another example, assume that we have the following method in MyClass
:
public void SetItem(Task task)
{
foreach (var subTasks in task.SubTasks)
{
..........
}
}
So should I force the developer to check task.SubTask == null
before the above loop and throw an ArgumentException
by a unit test like bellow? I mean is it a "MUST" that the developer checks SubTasks
value (and each property of input task
before working with it) to check whether it is null or not and throw ArgumentException
when the related property is null?
[Fact]
public void SetItem_WhenSubTasksIsNull_SetItemFromTask(Task task)
{
// Act and Assert
Assert.Throws<ArgumentException>(
()=> new MyCalss().SetItem(new Task(){
SubTasks=null
}));
}
Is it a correct approach? Should I force the developers to write the same conditional codes in his/her related method to pass my unit test or I should not consider these cases as TestCases?
Maybe developers say:
- Normally our codes returns these exceptions if these fields have invalid value (for example when we wrote
arg1.childA.childB
andchildA
is null, it returns the appropriate exception itself), so it is not necessary to we check their values and raise the related same exception when their values are invalid.- Checking all fields at first forces us to refactor hundreds of methods to add a lot of conditional codes in them and it take many time and
- In many cases we know that child properties filled with correct values because we ourselves provide their values in other methods and we include required fields in them
- Also this makes the codes of each method more crowded and reduces readability
On the other hand, we see in the image that in large projects usually there are a lot of fields in an input model that checking them is possible and it cause writing many lines of codes for most of the unit test such as what you see in the above image.
So, What is the correct approach and answer to these issues?