-1

我有一个控制器动作

  [HttpPost]
   public ActionResult CreateFocus(FocusFormModel focus)
    {
        var errors = focusService.CanAddFocus(Mapper.Map<FocusFormModel, Focus>(focus)).ToList();

        ModelState.AddModelErrors(errors);
        if (ModelState.IsValid)
        {
            focusService.CreateFocus(Mapper.Map<FocusFormModel, Focus>(focus));
            var createdfocus = focusService.GetFocus(focus.FocusName);
            return RedirectToAction("Focus", new { id = createdfocus.FocusId });
        }
        return View("CreateFocus", focus);
    }

此操作工作正常,但是当我编写单元测试时它显示错误

你调用的对象是空的

单试是

 [Test]
    public void Create_Focus()
    {
        // Arrange                    
        GroupController controller = new GroupController(groupService);
        // Act


        FocusFormModel focus = new FocusFormModel();
           focus.GroupId  = 1;
            focus.FocusName = "t";
            focus.Description = "t";

        Mapper.CreateMap<FocusFormModel, Focus>().ForAllMembers(opt => opt.Ignore());
        Mapper.AssertConfigurationIsValid();
        var result = (RedirectToRouteResult)controller.CreateFocus(focus);
          Assert.AreEqual("Index", result.RouteValues["action"]);
     }

我的模型描述如下

public class Focus
{
    public int FocusId { get; set; }

    [StringLength(50)]
    public string FocusName { get; set; }

    [StringLength(100)]
    public string Description { get; set; }

    public int GroupId { get; set; }

    public virtual Group Group { get; set; }

    public DateTime CreatedDate { get; set; }



    public Focus()
    {
        CreatedDate = DateTime.Now;
    }
}

我正在写我的视图模型

public class FocusFormModel
{
    public int FocusId { get; set; }
    [Required(ErrorMessage = "*")]
    [StringLength(50)]
    public string FocusName { get; set; }
    [Required(ErrorMessage = "*")]
    [StringLength(100)]
    public string Description { get; set; }

    public int GroupId { get; set; }

    public virtual Group Group { get; set; }

    public DateTime CreatedDate { get; set; }

    public FocusFormModel()
    {
        CreatedDate = DateTime.Now;
    }
}

谁能帮帮我吗

4

1 回答 1

0

这一行实际上提供了 2 次获得空引用异常的机会:

var errors = focusService.CanAddFocus(Mapper.Map<FocusFormModel, Focus>(focus)).ToList();

首先focusService可能是null

如果 focusService 不为空,则方法调用CanAddFocus(Mapper.Map<FocusFormModel, Focus>(focus))可能会返回null

那只是假设。
正如 Greg Smith 所说,堆栈跟踪在这里会很有帮助。

于 2012-12-02T09:26:29.110 回答