Search code examples
c#unit-testingtaskvs-unit-testing-framework

How to return from System.Threading.Tasks.<string> method in UnitTesting


I have a method with the following signature.

Task<string> Post(PartyVM model);

I am writing a unit test class by using a following method to test the above Post method.

        mockPartyManager.Setup(mr => mr.Post(It.IsAny<PartyVM>())).Returns(
           (PartyVM target) =>
           {
               if (target.PartyID.Equals(default(int)))
               {
                   target.Name = "NewP";
                   target.Status = "ACTIVE";
                   target.PartyRoleID = msoList.Count() + 1;
                   partyList.Add(target);
               }
               else
               {
                   var original = partyList.Where(q => q.PartyID == target.PartyID).Single();

                   if (original == null)
                   {
                       return "Execution failed";
                   }

                   original.Name = target.Name;
                   original.Status = target.Status;
               }

               return "Execution Successful";
           });
        this.MockMSOManager = mockPartyManager.Object;
    }

I am getting error messages when I try to return strings.

Error 45 Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task'

How can I resolve this issue.

Error


Solution

  • Try using the Task.FromResult<TResult> method. From MSDN:

    Creates a Task that's completed successfully with the specified result.

    return Task.FromResult("Execution failed");