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

            
        }

    }

}

原文地址:https://www.cnblogs.com/xhan/p/1494766.html