Reputation: 560
I'm new to Moq and I'm struggling with this error. I'm not quite sure why I'm receiving the error that I am getting. I was following along with the test code found here.
Error:
Moq.MockException: Expected invocation on the mock at least once, but was never performed: c => c.PostAsync(Mock.Object, "You send abc which was 3 characters")
Code
MyTests.cs
[TestClass]
public class MyTests
{
private Mock<IChatHelper> _chat;
private RootDialog _dialog;
private Mock<IDialogContext> _context;
public LUISDialogTests()
{
_chat = new Mock<IChatHelper>();
_context = new Mock<IDialogContext>();
_dialog = new RootDialog(_chat.Object);
}
//[SetUp]
//public void SetUp()
//{
// _chat = new Mock<IChatHelper>();
// _dialog = new RootDialog(_chat.Object);
// _context = new Mock<IDialogContext>();
//}
[TestMethod]
public async Task Test_CustomerService_Message_LengthAsync()
{
var message = Activity.CreateMessageActivity();
message.Text = "abc";
_chat.Setup(c => c.PostAsync(_context.Object, message.Text));
await _dialog.MessageReceivedAsync(_context.Object, Awaitable.FromItem(message));
_chat.Verify(c => c.PostAsync(_context.Object, "You send abc which was 3 characters"), Times.AtLeastOnce); // Fails here
}
}
RootDialog.cs
[Serializable]
public class RootDialog : IDialog<object>
{
private IChatHelper _chat;
public RootDialog(IChatHelper chat)
{
_chat = chat;
}
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var message = await result as Activity;
int length = (message.Text ?? string.Empty).Length;
await _chat.PostAsync(context, $"You sent {message.Text} which was {length} characters");
context.Wait(MessageReceivedAsync);
}
ChatHelper.cs
public interface IChatHelper
{
Task PostAsync(IDialogContext context, string message);
}
[Serializable]
public class ChatHelper : IChatHelper
{
public async Task PostAsync(IDialogContext context, string message)
{
await context.PostAsync(message);
}
}
One thing to note:
Upvotes: 2
Views: 5202
Reputation: 5775
It's a one character typo in the message you are expecting. Your code under test does this:
await _chat.PostAsync(context, $"You sent {message.Text} which was {length} characters");
and you are verifying that this happened:
_chat.Verify(c => c.PostAsync(_context.Object, "You send abc which was 3 characters"), Times.AtLeastOnce); // Fails here
Can you spot the difference in the two strings? sent
!= send
. Change one or other, and it'll probably start working.
Upvotes: 4