测试:mock对象

using System;
using System.Text;
using System.Threading;
using System.Messaging;

namespace QueueSpace
{

    //外部依赖的接口,它屏蔽了mock对象和真对象
    class Queue
    {
        public virtual object readMessage()
        {
            return null;
        }
    }

    //mock对象,模拟真对象的行为
    class TestQueue : Queue
    {
        private int index = 0;
        private object[] Data = { "hello","world"};
        public override object readMessage()
        {

            while (index < Data.Length)
            {
                object data = Data[index];
                index++;
                return data;
            }

            Thread.Sleep(60*60*60);
            return null;
        }
    }
    
    //真正的业务对象
    class WorkQueue : Queue
    {
        MessageQueue queue = null;

        public WorkQueue()
        {
            string queueName = ".\\Private$\\MSMQDemo";
            if (MessageQueue.Exists(queueName))
            {
                queue = new MessageQueue(queueName);
            }
            else
            {
                queue = MessageQueue.Create(queueName, false);
                queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
            }
        }

        public override object readMessage()
        {
            System.Messaging.Message message = queue.Receive();
            string s =(string)message.Body;
            return (object)s;
        }
    }

    //对象工厂
    class QueueFactory
    {
        public static Queue makeQueue()
        {
           return new TestQueue();
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QueueSpace;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue queue = QueueFactory.makeQueue();
            while (true)
            {
                object msg = queue.readMessage();
                Console.WriteLine((string)msg);
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/code-style/archive/2012/09/22/2698210.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值