GJaminon
1/7/2017 - 5:18 PM

RabbitMQ HelloWorld

using System;
using System.Diagnostics;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RabbitMQ.Client;
using System.Configuration;

namespace QueueTests
{
    [TestClass]
    public class HelloWorld
    {
        private DevOpsGatewayEngine.DevOpsGatewayEngine _engine;
        private string _response;
        private string _messageSended;
        private string _queueName;

        [TestInitialize]
        public void Initialize()
        {
            _messageSended = "Hello";
            _queueName = ConfigurationManager.AppSettings.Get("QueueName");
            _engine = new DevOpsGatewayEngine.DevOpsGatewayEngine();
            _engine.Start();
            _engine._manager.OnMessageReceived = OnMessageReceived;
        }

        [TestMethod]
        public void HelloTest()
        {
            var factory = new ConnectionFactory() { HostName = ConfigurationManager.AppSettings.Get("QueueServer") };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: _queueName,
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                var body = Encoding.UTF8.GetBytes(_messageSended);

                channel.BasicPublish(exchange: "",
                                     routingKey: ConfigurationManager.AppSettings.Get("QueueName"),
                                     basicProperties: null,
                                     body: body);
                Trace.WriteLine(" [x] Sent {0}", _messageSended);
            }


            //TODO: Exctract / Refactor
            bool result = false;
            bool finished = false;
            Stopwatch stopwatch = Stopwatch.StartNew();
            while (stopwatch.Elapsed <= new TimeSpan(0,0,0,5) && finished == false)
            {
                if (this._response != null)
                {
                    Trace.WriteLine("Message received : " + _response);
                    finished = true;
                    result = this._response == this._messageSended;
                }
            }
            Assert.IsTrue(result);

        }

        private void OnMessageReceived(object sender, string message)
        {
            _response = message;
        }


        [TestCleanup]
        public void TestCleanup()
        {
            this._engine._manager.StopListening();
        }
    }


}