1

我在如何在易于测试的 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,但没有成功地以可测试的方式实现它。不太确定这是否含糊不清,但我已经阅读了很多,而不是更接近。

4

2 回答 2

0

单例绝对是你的问题 - 单例测试正在进入一个痛苦的世界。你应该实现一个外观模式来使这个测试变得友好。像这样的东西:

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.....);
    }
}
于 2012-11-25T18:34:08.517 回答
0

您的问题是您的服务是单例的。单例模式的问题是它不可测试。您应该使用依赖注入来获得服务。

于 2012-11-25T09:34:04.577 回答