单元测试模拟WCF客户端

时间:2012-11-25 00:21:35

标签: asp.net-mvc wcf mocking nunit

我在如何在易于测试的MVC站点中部署WCF客户端时遇到了严重问题。我正在努力设置模拟服务而不实际访问端点。

受测试网站的示例

public class ProfileController : ControllerExtended
{

    public ProfileController(IUserService membershipService, IDropDownService dropdownService, ISiteService siteService)
    {
        WCFService.Instance.Client = siteService; //Should maybe be a serpate service.
        _membershipService = membershipService;
        _dropDownService = dropdownService;
        _siteService = siteService;

    }

    public ActionResult Index()
    {
        UserComp profile = _siteService.ProfileGet(_sharedContext.CurrentUser.id);

        return View(new ProfileViewModel { Profile = profile });
    }
}

WCF Singleton(我认为我的WCF实现是我的问题,它应该在接口中吗?)

public sealed class WCFService
{

    public SiteServiceI Client { get; set; }

    #region Singleton

    static readonly WCFService query = new WCFService();

    static WCFService()
    {
    }

    WCFService()
    {
    }

    public static WCFService Instance
    {
        get { return query; }
    }

    #endregion
}

单元测试

[TestFixture]
public class UnitTest1
{
    private Mock<SiteService> mockSiteService;
    private Mock<IUserService> mockMembershipService;
    private Mock<IDropDownService> mockDropDown;
    private Mock<SiteServiceIClient> mockServiceClient; //new Mock<SiteServiceIClient>();


    //private Mock<WebService> mockWebService;

    [SetUp]
    public void SetUp()
    {
        mockSiteService = new Mock<ISiteService>();
        mockMembershipService = new Mock<IUserService>();
        mockDropDown = new Mock<IDropDownService>();
        mockServiceClient = new Mock<SiteServiceIClient>();

        mockWebService = new Mock<WebService>(mockServiceClient);
    }

    [Test]
    public void CheckHomeIndex_Controller()
    {

        var controller = new HomeController(mockMembershipService.Object, mockDropDown.Object, mockPTSearch.Object, mockServiceClient.Object); // mockServiceClient times out.

        Assert.AreEqual("this", "this");
    }
}

我认为错误正在发生,因为单例在初始化后立即设置服务。我试图实现一个单独的服务,纯粹是为了调用WCF,但没有成功地以可测试的方式实现它。不太确定这是否含糊不清,但我已经阅读了很多,而不是更接近。

2 个答案:

答案 0 :(得分:0)

您的问题是您的服务是单身人士。单例模式的问题在于它不可测试。您应该使用依赖注入来获取服务。

答案 1 :(得分:0)

单身人士肯定是你的问题 - 单身人士的测试正在进入痛苦的世界。您应该实现facade模式以使此测试更加友好。像这样:

public interface IServiceFacade
{
    Profile ProfileGet(int id);
}

public class ServiceFacade : IServiceFacade
{

    private WCFService _theRealService = new WCFService();

    public Profile ProfileGet(int id)
    {
        return _theRealService.ProfileGet(id);
    }
}



public class Some_Tests()
{
    public void Test_Stuff_Whatever()
    {

        Mock<IServiceFacade> _facade = new Mock<IServiceFacade>();

        _facade.SetUp(Whatever.....);
    }
}