• 使用NUnit和DynamicMock进行单元测试


    using System;
    using System.Collections.Generic;
    using System.Text;
    using NUnit.Framework;
    using NUnit.Mocks;
    namespace DynamicMockDemo
    {
        
    public class Person
        
    {
            
    public Person(int id, string name)
            
    {
                
    this.Id = id;
                
    this.Name = name;
            }

            
    private int id;

            
    public int Id
            
    {
                
    get return id; }
                
    set { id = value; }
            }

            
    private string name;

            
    public string Name
            
    {
                
    get return name; }
                
    set { name = value; }
            }

        }

        
    public interface IDB
        
    {
            Person GetPersonById(
    int id);
            IList
    <Person> GetPersons();
            
    void DeletePerson(int id);
        }

        [TestFixture]
        
    public class Dome
        
    {
            [Test]
            
    public void Test()
            
    {
                Person person1 
    = new Person(1,"aaa");
                Person person2 
    = new Person(2,"bbb");
                IList
    <Person> persons = new List<Person>();
                persons.Add(person1);
                persons.Add(person2);

                
    //创建Mock对象
                DynamicMock dbMock = new DynamicMock(typeof(IDB));
                
    //模拟GetPersonById方法,传入1,返回person1
                dbMock.ExpectAndReturn("GetPersonById", person1, 1); 
                
    //模拟GetPersons,返回persons
                dbMock.SetReturnValue("GetPersons", persons);
                
    //模拟 DeletePerson,传入3,抛出异常
                dbMock.ExpectAndThrow("DeletePerson"new Exception("删除失败"), 3); 
                
    //获取IDB接口的Mock对象实例
                IDB db = (IDB)dbMock.MockInstance;

                Person testPerson 
    = db.GetPersonById(1);
                Assert.AreEqual(person1.Name, testPerson.Name);

                IList
    <Person> testPersons = db.GetPersons();
                Assert.AreEqual(
    2, testPersons.Count);

                
    try
                
    {
                    db.DeletePerson(
    3);
                }

                
    catch (Exception e)
                
    {
                    Assert.AreEqual(
    "删除失败", e.Message);
                }

                
            }

        }

    }

  • 相关阅读:
    485串口接线
    mvc3 升级mvc5
    VB连接ACCESS数据库,使用 LIKE 通配符问题
    VB6 读写西门子PLC
    可用的 .net core 支持 RSA 私钥加密工具类
    解决 Win7 远程桌面 已停止工作的问题
    解决 WinForm 重写 CreateParams 隐藏窗口以后的显示问题
    解决安装 .net framework 发生 extracting files error 问题
    CentOS7 安装配置笔记
    通过特殊处理 Resize 事件解决 WinForm 加载时闪烁问题的一个方法
  • 原文地址:https://www.cnblogs.com/xhan/p/1494766.html
Copyright © 2020-2023  润新知