Moq错误:"模拟上的预期调用至少一次,但从未执行过#34;

时间:2018-06-13 16:07:33

标签: c# moq botframework

我是Moq的新手,我正在努力解决这个错误。我不太确定为什么我收到了我得到的错误。我跟着发现here的测试代码。

错误:

  

Moq.MockException:   模拟上的预期调用至少一次,但从未执行过:c => c.PostAsync(Mock.Object,"你发送的abc是3个字符")

代码

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);
    }
}

有一点需要注意:

  • 以下代码建议使用[TestFixture]而不是[TestClass]。当Fixture被添加时,VS无法看到测试,所以我换了测试类

1 个答案:

答案 0 :(得分:3)

这是你期待的消息中的一个字符错字。您正在测试的代码执行此操作:

await _chat.PostAsync(context, $"You sent {message.Text} which was {length} characters");

您正在验证是否发生了这种情况:

_chat.Verify(c => c.PostAsync(_context.Object, "You send abc which was 3 characters"), Times.AtLeastOnce); // Fails here

你能发现两个字符串的区别吗? sent!= send。改变一个或其他,它可能会开始工作。