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

5.7k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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");
0
On

Your method returns Task, not string. Use Task.FromResult to correct the error.

https://msdn.microsoft.com/es-es/library/hh194922(v=vs.110).aspx