0

我为 edit_get 操作编写了一个单元测试我的控制器操作是

 public class GroupController : Controller
  {
     private readonly IGroupService groupService;
     public GroupController(IGroupService groupService)
     {
       this.groupService = groupService;
      }
      public ActionResult EditGroup(int id)
       {
          var group = groupService.GetGroup(id);
          CreateGroupFormModel editGroup = Mapper.Map<Group, CreateGroupFormModel>(group);
          if (group == null)
           {
            return HttpNotFound();
          }
           return View("_EditGroup", editGroup);
       }

控制器动作工作正常。但是当我编写单元测试时它失败了我的测试是

[Test]
    public void Edit_Get_ReturnsView()
    {
    //Arrange
    CreateGroupFormModel group = new CreateGroupFormModel()
    {
     GroupId = 2, 
     GroupName = "Test",

     Description = "test" };
     GroupController controller = new GroupController();
    var fake = groupService.GetGroup(2);
    groupRepository.Setup(x => x.GetById(2)).Returns(fake);
    Mapper.CreateMap<CreateGroupFormModel, Group>().ForAllMembers(opt => opt.Ignore());
    Mapper.AssertConfigurationIsValid();
    ViewResult actual = controller.EditGroup(2) as ViewResult;
    Assert.IsNotNull(actual, "View Result is null");
   }

谁能帮我。测试失败

Expected Not Null
actual Null
4

1 回答 1

1

在您正在调用的控制器操作中var group = groupService.GetGroup(id);,这不是很清楚这groupService是从哪里来的。在您的单元测试中,您必须模拟它。为此,您GroupController必须将此依赖项作为构造函数注入。

同样在您的单元测试中,您似乎已经声明了一些group从未使用过的变量。

例如:

public class GroupController: Controller
{
    private readonly IGroupService groupService;
    public GroupController(IGroupService groupService)
    {
        this.groupService = groupService;
    }

    public ActionResult EditGroup(int id)
    {
        var group = this.groupService.GetGroup(id);
        CreateGroupFormModel editGroup = Mapper.Map<Group, CreateGroupFormModel>(group);
        if (group == null)
        {
            return HttpNotFound();
        }
        return View("_EditGroup", editGroup);
    }
}

现在在您的单元测试中,您可以模拟此组服务并提供对 GetGroup 方法结果的期望:

[Test]
public void Edit_Get_ReturnsView()
{
    // arrange
    var group = new CreateGroupFormModel 
    {
        GroupId = 2,
        GroupName ="Test", 
        Description ="test" 
    };
    var groupServiceMock = new Mock<IGroupService>();
    groupServiceMock.Setup(x => x.GetGroup(group.GroupId)).Returns(group);
    var sut = new GroupController(groupServiceMock.Object);
    Mapper.CreateMap<CreateGroupFormModel, Group>().ForAllMembers(opt => opt.Ignore());
    Mapper.AssertConfigurationIsValid();

    // act
    var actual = sut.EditGroup(group.GroupId) as ViewResult;

    // assert
    Assert.IsNotNull(actual);
    Assert.IsInstanceOfType(typeof(ViewResult), actual);
}
于 2012-11-21T06:44:27.400 回答