I need to write some unit test cases to test my code in C# Visual Studio Team Test framework. Below is the method I want to test:
public static ObjectID CreateObjectID(ObjectID xrmObjectID)
{
return new ObjectID
{
Id = xrmAssociation.ID != null ? xrmAssociation.ID.Id : Guid.Empty;
};
}
In the above method, I need to write unit test cases to cover the conditional statements, for example:
Id = xrmAssociation.ID != null ? xrmAssociation.ID.Id : Guid.Empty;
So I wrote the following unit test method:
namespace WebApi.Test
{
[TestClass]
public class ApiTest
{
[TestMethod]
[ExpectedException(typeof(NullReferenceException), "A userId of null was inappropriately allowed.")]
public void CreateObjectIDShouldCheckConditionalBranch()
{
Xrm.objectID Input = new Xrm.objectID();
Input = null;
WebApiRole.Api.CreateObjectID(Input);
var expected = default(WebApi.ObjectID);
Assert.IsTrue(expected == WebApi.CreateObjectID(Input), "Failed");
}
}
}
This test passed, but it is actually not testing what I intend to test i.e. It should assign "Guid.Empty" when "null" is being passed. It just throws the exceptions of NullReference and thus the test passes.
I'd suggest writing one test for each separate case. That way, you can more easily tweak the testing code should requirements change.
I'd proceed like this (and I'll also take a guess and assume you're modelling Dynamics CRM, judging by the data)
and so on and so forth, two tests for each field, one to test the
true
side of the conditional and one for thefalse
side (a couple of generic methods, one for OptionSet fields and one for EntityReference fields could be built and called several times, making the code short and fast to write).Also, I think you should tweak
CreateAssociationFromXrm
to make it throw anArgumentException
ifinput
isnull
(a couple tests of specifically that are of course to be written beforehand).