Rhino Mocks Func断言测试

时间:2012-08-08 06:40:24

标签: asp.net-mvc-3 unit-testing tdd rhino-mocks

我需要测试在方法列表ex:

中调用特定的Func
public class ProductController : BaseController
    {
        private readonly Func<IProductRepository> prodRepo;
        public ProductController(Func<IProductRepository> _prodRepo)
       {
            prodRepo = _prodRepo;
       } 
        public ActionResult List(string applicationID)
        {
            var products = prodRepo().GetForApp(applicationID).ToList();
            return PartialView("_List",products);
        }
}

在这种情况下,我需要验证是否已调用 prodRepo()。GetForApp(applicationID)

2 个答案:

答案 0 :(得分:0)

我建议你用 Arrange-Act-Assert 样式编写测试。您可以在Ayende's blog

了解更多信息

安排阶段

首先定义MockRepository和期望:

var mockRepository = new MockRepository();

var repository = mockRepository.StrictMock<IProductRepository>();

using(mockRepository.Record())
{
    repository.Expect(x => x.GetForApp(Arg<string>.Is.Anything)).Return(new string[0]).Repeat.Once();
}

      var productController = new ProductController((Func<IProductRepository>)(() => repository));

行动阶段

执行操作:

productController.List("testApplicationID");

断言阶段

验证结果:

repository.VerifyAllExpectations();

缺少界面IProductRepository

public interface IProductRepository
{
    IEnumerable<string> GetForApp(string applicationID);
}

答案 1 :(得分:0)

你真的需要验证是否调用了Func?或者您是否需要验证ProductController是否正确检索产品?

如果是后者,只需设置一个模拟IProductRepository来返回一些产品,通过lambda传递它,并断言你得到的产品是正确的。通常,如果有东西提供信息(act / arrange / assert中的“排列”阶段,或者给定/ when / then中的“给定”阶段)那么你想要一个stub rather than a mock

您真正需要使用模拟并验证某些内容已被调用的唯一时间是被测试的类承担责任 - 例如,将产品保存在存储库中。

另外,请查看Moq ...在Moq IMO中设置存根更容易。