模拟单元测试的方法

本文关键字:方法 单元测试 模拟 | 更新日期: 2023-09-27 18:05:39

我想模拟下面的方法,它接受参数,以便使用fake和shims进行单元测试。我不知道这对我来说是什么新鲜事。如果有什么建议,我会很有帮助的。

public string Renotify(int[] userIds)
{
     var notify = new NotificationPublisher();
     var message = "A request has been awaiting for your approval. Please check the application for details to approve the request ";
     var subject = "Logos Approval Notification";
     if (userIds.Length < 1)
         return "Please select users to notify";
     List<NotificationUser> userList = userIds.Select(t => new NotificationUser { userId = t }).ToList();
     notify.SendNotification(userList, message, subject);
     return "Success - Approvers Renotified";
}

模拟单元测试的方法

你不能模拟一个方法,比如说,它没有意义,你可以模拟你想要测试的东西使用的接口。

相反,你可以,但我不相信这是你真正想要的。

public class Foo
{
    private readonly IBar _bar;
    public Foo(IBar bar)
    {
        _bar = bar;
    }
    public void MyMethodToTest()
    {
        // Some stuff
        _bar.SomethingToBeMocked();
        //some more stuff
    }
}

IBar接口:

public IBar
{
    void SomethingToBeMocked();
}

模拟接口IBar,然后在IBar.SomethingToBeMocked()上设置预期的调用