Moq测试与通用接口 [英] Moq test with generic interface

查看:80
本文介绍了Moq测试与通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public interface IWebAPIAsync<t>
    {
        Task<List<t>> Load();
        Task Create(T obj);
        Task<t> Read(int key);
        Task Update(int key, T obj);
        Task Delete(int key);
    }
 public class WebAPITest<t>
    {
        #region Instance fields
        private IWebAPIAsync<t> _webAPI;

        #endregion

        #region Constructor

        public WebAPITest(IWebAPIAsync<t> webApi)
        {
            _webAPI = webApi;

        }

        public WebAPITest()
        {
        }
        #endregion

        #region Test methods for all five REST API methods
        public async Task RunAPITestLoad()
        {
            await LoadAndPrint();
        }

        public async Task RunAPITestCreate(T obj)
        {
            await RunAPITest(() => _webAPI.Create(obj));
        }

        public async Task RunAPITestRead(int key)
        {
            Task<t> readTask = _webAPI.Read(key);
            await readTask;
            PrintSingleRecord(readTask.Result);
        }

        public async Task RunAPITestUpdate(int key, T obj)
        {
            await RunAPITest(() => _webAPI.Update(key, obj));
        }

        public async Task RunAPITestDelete(int key)
        {
            await RunAPITest(() => _webAPI.Delete(key));
        }
        #endregion

        #region Private helper methods for test execution
        private async Task RunAPITest(Func<task> APIMethod)
        {

            await APIMethod();

        }

        private async Task LoadAndPrint()
        {
            Task<List<t>> loadTask = _webAPI.Load();
            await loadTask;
            PrintMultipleRecords(loadTask.Result);
        }

        private void PrintMultipleRecords(List<t> records)
        {

            foreach (var record in records)
            {
                Console.WriteLine(record);
            }

        }

        private void PrintSingleRecord(T record)
        {
            {
                Console.WriteLine(record);
            }
        }


    }
}





我尝试过:



var mock = new Mock< IWebAPIAsync< task1>>();

mock.Setup(x => x.Create(It.IsAny< task1>()));

mock.Verify();



What I have tried:

var mock = new Mock<IWebAPIAsync<task1>>();
mock.Setup(x => x.Create(It.IsAny<task1>()));
mock.Verify();

推荐答案

模拟Create方法不会测试Create方法。您模拟界面以测试使用您的界面的代码,通常是因为您的界面访问数据存储而您正在编写单元测试,而不是集成测试
Mocking the Create method does not test the Create method. You mock your interface in order to test code that USES your interface, typically because your interface accesses a data store and you're writing unit tests, not integration tests


这篇关于Moq测试与通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆