WCF Webプログラミングモデルの学習テスト Part1

WCFのWeb プログラミング モデルの学習テストを書いてみた。まずは、簡単な Hello World なサービスから。

using System;
using System.IO;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace LearningWCFTests
{
    [TestClass]
    public class SimpleTest
    {
        ...

        [ServiceContract]
        public interface IHelloWorld
        {
            [OperationContract]
            [WebGet(UriTemplate = "helloworld")]
            string GetHello();
        }

        public class HelloWorld : IHelloWorld
        {
            public string GetHello()
            {
                return "Hello REST World!!";
            }
        }

        private static readonly Uri HostingBaseUri = new Uri("http://localhost:8000");
        private static readonly Uri ClientBaseUri = new Uri("http://localhost:8000");
        private WebServiceHost host_;

        [TestInitialize]
        public void サービスホスティングの開始()
        {
            host_ = new WebServiceHost(typeof(HelloWorld), HostingBaseUri);
            host_.Open();
        }

        [TestCleanup]
        public void サービスホスティングの終了()
        {
            if (host_.State != CommunicationState.Closed)
                host_.Close();
        }

        [TestMethod]
        public void クライアント側でWebChannelFactoryでサービスにアクセスできるべき()
        {
            using (WebChannelFactory<IHelloWorld> cf = new WebChannelFactory<IHelloWorld>(ClientBaseUri))
            {
                IHelloWorld channel = cf.CreateChannel();
                Assert.AreEqual<string>("Hello REST World!!", channel.GetHello());
            }
        }

        [TestMethod]
        public void 生HTTPのGETでレスポンスが返されるべき()
        {
            UriTemplate template = new UriTemplate("helloworld");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(template.BindByPosition(ClientBaseUri));
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Assert.AreEqual<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);

            string responseBody = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Hello REST World!!</string>";

            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                Assert.AreEqual<string>(responseBody, reader.ReadToEnd());
            }
        }
    }
}