gpt4 book ai didi

c# - 模拟对象仍在调用服务

转载 作者:太空狗 更新时间:2023-10-29 23:23:13 24 4
gpt4 key购买 nike

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

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);
}

它使用这个 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;
}

这是我使用 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));
}
}

我的问题是,当我运行测试时,服务仍在被调用。我已经使用 Fiddler 验证了这一点,还调试了测试并检查了用我们服务的测试数据填充的“结果”的值。

编辑:

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

[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));
}
}

最佳答案

请确认您使用的是正确的 JustMock 程序集。有几个不同的(VisualBasic、Silverlight、JustMock)。 JustMock 是您应该包含在项目中的那个。

未能包含正确的将导致您描述的行为(方法未被正确 stub )。

关于c# - 模拟对象仍在调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19364487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com