如何测试服务不可用性和引发的http错误

时间:2014-08-07 22:02:18

标签: c# visual-studio unit-testing

我对单元测试很新,想要在服务不可用时进行模拟/测试,以确保抛出正确的错误。

方案

REST API,通过C#中的LDAP / DirectorySearcher查询Active Directory用户帐户。我看到三种可能的结果:找到用户,找不到用户,服务不可用(DirectorySearcher)。我为此设置了三个测试,但是一个总是失败,这取决于我是否连接到域。连接后,测试#1,#2成功。断开测试#2时,#3成功。我的测试是否过度杀伤,因为DirectoryServices库已经可靠了?我的目的是确保Web服务器在失去查询Active Directory的能力时抛出异常。

控制器

using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Web.Http;

namespace IdentitiesApi.Controllers
{
    public class UsersController : ApiController
    {
        // GET api/users/?username=admin
        public SearchResult Get([FromUri]string userName)
        {
            using (var searcher = new DirectorySearcher())
            {
                searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", userName);

                try
                {
                    SearchResult user = searcher.FindOne();

                    if (user == null)
                    {
                        var response = new HttpResponseMessage(HttpStatusCode.NotFound)
                        {
                            Content = new StringContent(string.Format("No user with username = \"{0}\" found.", userName)),
                            ReasonPhrase = "User Not Found"
                        };

                        throw new HttpResponseException(response);
                    }
                    else
                    {
                        return user;
                    }

                }
                catch (COMException)
                {
                    var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                    {
                        Content = new StringContent("The directory service could not be contacted. Please try again later."),
                        ReasonPhrase = "Directory Service Unavailable"
                    };

                    throw new HttpResponseException(response);
                }
            }
        }
    }
}

单元测试

using System;
using System.DirectoryServices;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Web.Http;
using IdentitiesApi.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace IdentitiesApi.Test
{
    [TestClass]
    public class UsersTest
    {
        [TestMethod]
        public void Single_AD_User()
        {
            // arrange
            var controller = new UsersController();
            SearchResult searchResult;

            string userName = "admin"; // existing user name
            string expected = "admin";
            string actual = "";

            // act
            searchResult = controller.Get(userName);

            // assert
            foreach (object value in searchResult.Properties["samAccountName"])
            {
                actual = value.ToString();
            }

            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        [ExpectedException(typeof(HttpResponseException))]
        public void AD_User_Not_Found_Exception()
        {
            // arrange
            var controller = new UsersController();
            SearchResult searchResult;

            string userName = "?"; // invalid user name

            // act
            try
            {
                searchResult = controller.Get(userName);
            }
            catch (HttpResponseException ex)
            {
                // assert
                Assert.AreEqual(HttpStatusCode.NotFound, ex.Response.StatusCode);
                throw;
            }
        }

        [TestMethod]
        [ExpectedException(typeof(HttpResponseException))]
        public void AD_Service_Unavailable_Exception()
        {
            // arrange
            var controller = new UsersController();
            SearchResult searchResult;

            string userName = "admin";

            // act
            searchResult = controller.Get(userName);
        }
    }
}

1 个答案:

答案 0 :(得分:4)

测试类似这样的东西的最好方法是使用DirectorySearcher的依赖注入,然后在单元测试中使用mock。

看起来有一个IDirectorySearcher接口,虽然我不知道DirectorySearcher是否实现了它。无论如何,这可能超出了你的要求,这就是我的建议:

  • Keep your controllers lightweight。现在,您的行动中有大量不可重复使用的业务逻辑。您正在捕获COM异常,并且您的控制器“知道”低级AD工作。相反,我会编写一个包装器来处理它,并抛出一个通用异常。您可以避免大量重复的代码(两个异常的额外抛出),如果您更改了使用AD的方式,则可以在一个位置执行此操作。

  • 将包装器注入控制器。这将允许您模拟服务,因此您可以通过您的操作测试所有不同的路径。

重写控制器:

public class UsersController : ApiController
{
    private IDirectorySearcher _searcher;

    public UsersController(IDirectorySearcher searcher)
    {
        _searcher = searcher;
    }

    // GET api/users/?username=admin
    public SearchResult Get([FromUri]string userName)
    {
        try
        {
            return _searcher.FindSAMAccountName(userName);
        }

        catch (ADException ex)
        {
            var response = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = ex.Content,
                ReasonPhrase = ex.Reason
            };

            throw new HttpResponseException(response);
        }
    }
}

然后你的单元测试(在这种情况下,我使用moq作为我的模拟库):

    [TestMethod]
    [ExpectedException(typeof(HttpResponseException))]
    public void AD_User_Not_Found_Exception()
    {
        var searcher = new Mock<IDirectorySearcher>();

        searcher.Setup(x => x.FindSAMAccountName(It.IsAny<string>()).Throws(new ADException());

        var controller = new UsersController(searcher.Object);

        try
        {
            SearchResult searchResult = controller.Get("doesn't matter. any argument throws");
        }
        catch (HttpResponseException ex)
        {
            // assert
            Assert.AreEqual(HttpStatusCode.NotFound, ex.Response.StatusCode);
            throw;
        }
    }

使用模拟的好处在于,对于每个单元测试,您可以更改Setup()调用以返回您想要的任何内容。它可以返回SearchResult,或抛出异常,或者什么也不做。你甚至可以使用

searcher.Verify(x => x.FindSAMAccountName(It.IsAny<string>()), Times.Once())

验证调用恰好发生了一次(或者没有,或者其他什么)。

这可能比你要求的要多,但总的来说,每层的复杂性越低,每层的单元测试就越容易。