模拟对象仍然打电话给服务

mmc*_*han 5 c# wcf unit-testing justmock asp.net-mvc-4

所以我正在为我们的MVC4应用程序编写测试,并且我正在专门测试Controller操作.正如我在标题中提到的,测试仍然命中服务(WCF)而不是返回测试数据.我有这个控制器:

public class FormController : Controller
{
    public SurveyServiceClient Service { get; set; }
    public SurveyDao Dao { get; set; }

    public FormController(SurveyServiceClient service = null, SurveyDao dao = null)
    {
        this.Service = service ?? new SurveyServiceClient();
        this.Dao = dao ?? new SurveyDao(Service);
    }

    //
    // GET: /Form/

    public ActionResult Index()
    {
        var formsList = new List<FormDataTransformContainer>();
        Dao.GetForms().ForEach(form => formsList.Add(form.ToContainer()));

        var model = new IndexViewModel(){forms = formsList};
        return View("Index", model);
    }
Run Code Online (Sandbox Code Playgroud)

它使用这个DAO对象:

public class SurveyDao
{
    private readonly SurveyServiceClient _service;
    private readonly string _authKey;

    public SurveyDao(SurveyServiceClient serviceClient)
    {
        _service = serviceClient;
    }

    ....

    public FormContract[] GetForms()
    {
        var forms = _service.RetrieveAllForms();
        return forms;
    }
Run Code Online (Sandbox Code Playgroud)

这是我使用JustMock的测试,GetForms()上的模拟返回一个辅助类中的一些测试数据:

[TestClass]
public class FormControllerTest
{
    private SurveyDao mockDao;
    private SurveyServiceClient mockClient;

    public FormControllerTest()
    {
        mockClient = Mock.Create<SurveyServiceClient>();
        mockDao = Mock.Create<SurveyDao>(mockClient);
    }

    [TestMethod]
    public void TestIndexAction() 
    {
        //Arrange
        var controller = new FormController(mockClient, mockDao);
        Mock.Arrange(() => mockDao.GetForms()).Returns(TestHelpers.FormContractArrayHelper);

        //Act
        var result = controller.Index() as ViewResult;

        //Assert
        Assert.IsInstanceOfType(result.Model, typeof(IndexViewModel));
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我运行测试时,仍在调用服务.我已经使用Fiddler验证了这一点,并调试了测试并检查了"result"的值,该值填充了我们服务的测试数据.

编辑:

我已经将测试构造函数更改为[TestInitialize]函数,因此Test现在看起来像这样:

[TestClass]
public class FormControllerTest
{
    private SurveyDao mockDao;
    private SurveyServiceClient mockClient;

    [TestInitialize]
    public void Initialize()
    {
        mockClient = Mock.Create<SurveyServiceClient>();
        mockDao = Mock.Create<SurveyDao>(Behavior.Strict);
    }

    [TestMethod]
    public void TestIndexAction() 
    {
        //Arrange
        var controller = new FormController(mockClient, mockDao);
        Mock.Arrange(() => mockDao.GetForms()).Returns(TestHelpers.FormContractArrayHelper);

        //Act
        var result = controller.Index() as ViewResult;

        //Assert
        Assert.IsInstanceOfType(result.Model, typeof(IndexViewModel));
    }
}
Run Code Online (Sandbox Code Playgroud)