0

我有两个调用控制器的测试方法:
这个通过了:

  [Test]
    public void EditAction_Should_Redirect_When_Update_Successful()
    {

        // Arrange
        var controller = CreatePaperControllerAs("SomeUser");
        const int id = 2;

        FormCollection formValues = new FormCollection() {
            { "IM_Paper.Title", "Another value" },
            { "IM_Paper.Abstract", "Another description" }
        };

        controller.ValueProvider = formValues.ToValueProvider();

        // Act
        var result = controller.Edit(id, formValues) as RedirectToRouteResult;

        // Assert
        Assert.AreEqual("Details", result.RouteValues["Action"]);
        Assert.AreEqual(id, result.RouteValues["id"]);
    }

这个失败了:

 [Test]
    public void EditAction_Should_Redisplay_With_Errors_When_Update_Fails()
    {

        // Arrange
        var controller = CreatePaperControllerAs("SomeUser");
        int id = 1;

        FormCollection formValues = new FormCollection() {
            { "IM_Paper.Year","xxx"}
        };

        controller.ValueProvider = formValues.ToValueProvider();

        // Act
        var result = controller.Edit(id, formValues) as ViewResult;

        // Assert
        Assert.IsNotNull(result, "Expected redisplay of view");
            Assert.IsTrue(result.ViewData.ModelState.IsValid, "Expected Errors");
    }

控制器中的动作结果是

        [HttpPost, Authorize]
    public ActionResult Edit(int id, FormCollection collection)
    {

        IM_Paper paper = _paperRepository.GetPaperById(id);

        if (!paper.IsPostedByUser(User.Identity.Name))
            return View("InvalidOwner");
     try
     {
            UpdateModel(paper, "IM_Paper" );

            _paperRepository.Save();

            return RedirectToAction("Details", new { id = paper.PaperId });
        }
        catch
        {
            return View(paper);
        }
    }

但是,try-catch 块永远不会捕获异常(“IM_Paper.Year”应该是一个 int)。所以控制器总是将 Action 结果作为 RedirectToAction 返回。即使是第一个,内存中的数据也没有改变。

你知道为什么会这样吗?对于“IM_Paper”类,我使用 POCO 生成器并从实体框架生成。该类如下所示:

    public partial class IM_Paper
{
    #region Primitive Properties

    public virtual int PaperId
    {get;set;}

    public virtual string Author
    {get;set;}

    public virtual Nullable<int> Year
    {get;set;
    } ...  
4

1 回答 1

0

找到了答案,我没有将属性绑定到 IM_Paper 类。

于 2011-03-24T03:22:15.110 回答