zoukankan      html  css  js  c++  java
  • 使用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);
                }

                
            }

        }

    }

  • 相关阅读:
    SQL计算生日所属的星座 XuZhao
    IIS 操作系统 .net FrameWork 的一些常见问题
    Python面向对象4.实例属性、实例方法
    Python面向对象6.init方法
    Python面向对象3.定义类、创建对象
    源码部署zabbix4.0监控
    IE6 Select控件挡住DIV内容解决办法
    转自网上的c#日期大全
    已更新或者删除的行值不能使该行成为唯一行(sql2005) 解决办法
    asp 多行多列加分页代码
  • 原文地址:https://www.cnblogs.com/xhan/p/1494766.html
Copyright © 2011-2022 走看看