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

                
            }

        }

    }

  • 相关阅读:
    MSI文件静默安装
    C#文本文件或其他文件新内容追加
    VS2015在线安装包
    Hive创建表时添加中文注释后乱码问题
    scala获取字符串首字符和尾字符
    kafka topic常用命令
    supervisord实例配置
    pandas写数据进入数据库
    supervisord初体验
    python3 安装impyla相关的包
  • 原文地址:https://www.cnblogs.com/xhan/p/1494766.html
Copyright © 2011-2022 走看看