Search code examples
c#.net.net-6.0mstest

how to write unit test case for ternary condition using MSTest C# .Net 6


public static Transaction Update(Transaction authData, CreateArguments arguments)
{
    if (authData == null) return null;

    **authData.CampaignId = string.IsNullOrWhiteSpace(arguments.CampaignId) ? authData.CampaignId : arguments.CampaignId;
    authData.Status = string.IsNullOrWhiteSpace(arguments.Status) ? authData.Status : arguments.Status;**
    authData.DateModified = DateHelper.GpgNow();
    return authData;
}

[TestMethod]
public void Update_WhenTransactionObjIsNull()
{
    var argument = new Transaction.CreateArguments();
    var response = Transaction.Update(null, argument);
    Assert.IsNull(response);
}

I have the Update() method and setting CampaignId and Status using ternary condition. and below [TestMethod] is written. How can i add unit test case for those ternary condition. Please help


Solution

  • Most unit test frameworks allow passing data to unit tests. In MSTest this is done using the DataRow attribute. You can pass different value combinations for campaign and status and check whether the resulting object's properties match what you expected.

    You can test the method for different Campaign ID values like this

    [TestMethod]
    [DataRow("","DefaultID")]
    [DataRow(null,"DefaultID")]
    [DataRow("1234","1234")]
    public void Update_For_CampId(string? campId,string expectedCampId)
    {
        var transaction=new Transaction()
        {
            CampaignId="DefaultID",
            Status="DefaultStatus"
        };
        var argument = new Transaction.CreateArguments();
        
        argument.CampaignId=campId;
        argument.Status="SomeStatus";
    
        var response = Transaction.Update(transaction, argument);
    
        Assert.AreEqual(expectedCampId,response.CampaignId);
        Assert.AreEqual(expectedStatus,response.Status);
    }
    

    Testing Status is similar :

    [TestMethod]
    [DataRow("","DefaultStatus")]
    [DataRow(null,"DefaultStatus")]
    [DataRow("OK","OK")]
    public void Update_For_Status(string? status, string expectedStatus)
    {
        var transaction=new Transaction()
        {
            CampaignId="DefaultID",
            Status="DefaultStatus"
        };
        var argument = new Transaction.CreateArguments();
        
        argument.CampaignId="SomeID";
        argument.Status=status;
    
        var response = Transaction.Update(transaction, argument);
    
        Assert.AreEqual(expectedCampId,response.CampaignId);
        Assert.AreEqual(expectedStatus,response.Status);
    }