使用隔离框架构造伪对象进行单元测试

发表于:2012-9-18 10:54

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Jeff Wong    来源:51Testing软件测试网采编

  单元测试如下:

  d、UnitTest

using System;
using MonitorService;
using MonitorService.Impl;
using Ninject;
using NUnit.Framework;

namespace UnitTestApp
{
    [TestFixture]
    public class MonitorServiceTest_Manual
    {
        public ConfigFileMonitor CurrentFileMonitor
        {
            get;
            set;
        }

        public ILogService LogService
        {
            get;
            set;
        }

        public IEmailService EmailService
        {
            get;
            set;
        }

        [SetUp]
        public void SetUp()
        {
            using (var kernel = new StandardKernel(new ServiceModule()))
            {
                this.CurrentFileMonitor = kernel.Get<ConfigFileMonitor>();
                this.CurrentFileMonitor.LogService = kernel.Get<StubLogService>();
                this.CurrentFileMonitor.EmailService = kernel.Get<MockEmailService>();
            }
        }

        [Test]
        public void FileMonitor_Inject_GetInstance()
        {
            Assert.IsNotNull(CurrentFileMonitor, "ConfigFileMonitor is not initialized");
        }

        [Test]
        public void FileMonitor_LogService_Inject_GetInstance()
        {
            Assert.IsNotNull(CurrentFileMonitor.LogService, "ConfigFileMonitor stub LogService is not initialized");
        }

        [Test]
        public void FileMonitor_EmailService_Inject_GetInstance()
        {
            Assert.IsNotNull(CurrentFileMonitor.EmailService, "ConfigFileMonitor mock EmailService is not initialized");
        }

        [Test]
        public void Analyze_WebServiceThrows_SendEmail()
        {
            CurrentFileMonitor.LogService.ExToThrow = new NotImplementedException("fake exception");
            var shortFileName = "abc.txt";
            CurrentFileMonitor.Analyze(shortFileName);
            Assert.AreEqual("jeffwong@cnblogs.com", CurrentFileMonitor.EmailService.To);
            Assert.AreEqual("filename check", CurrentFileMonitor.EmailService.Subject);
            Assert.AreEqual("fake exception", CurrentFileMonitor.EmailService.Body);
            //Assert.AreEqual("fake object", CurrentFileMonitor.EmailService.Body);
        }

        [TearDown]
        public void TearDown()
        {
            this.CurrentFileMonitor = null;
        }

    }
}

  其中,服务调用我们通过Ninject实现解耦,为了简单看到效果,这里没有直接通过构造函数或者属性实现依赖注入。

  通过上面的说明我们确实可以得出这两个伪对象是有明显区别的,某些书洋洋洒洒毫不吝惜笔墨写了许多页,就专门介绍这两三个概念的异同,但是看的人依然云里雾里。

43/4<1234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号