C#获取CreatedAtRoute的返回对象

时间:2019-09-27 00:31:53

标签: c# unit-testing asp.net-core nunit

我有一个控制器方法,该方法返回CreatedAtRoute对象。如何提取返回的对象?

我的测试类(调用控制器):

[Test]
public void AddUser(){
  AppUser au= new AppUser();
  GreenCardController gc = new GreenCardController();
  ActionResult<AppUser> res = gc.UpdateArgosUser(au); //<-- How can I turn this into an AppUser object?
  //var temp=res.Value; //this didnt have the Object
  Assert.AreEqual(res.FirstName,"")
}

控制器方法:

public ActionResult<AppUser> UpdateArgosUser([FromBody]AppUser au)
{
     return CreatedAtRoute(nameof(GreenCardController.GetArgosUser), new 
                   { userid = au.UserId }, au);
}

当我在调试模式下res.Result.Value暂停此操作时,这似乎是我想要的,但出现错误:

  

ActionResult不包含“值”的定义

1 个答案:

答案 0 :(得分:0)

从返回的ActionResult<AppUser>中提取所需的值,转换为已知的类型以访问所需的成员。

由于控制器调用return CreatedAtRoute(...),因此您需要访问ActionResult<TResult>.Result属性以从控制器获取返回的ActionResult

从那里开始,要在对象结果中获取储值对象。

[Test]
public void AddUser(){
    //Arrange
    AppUser expected = new AppUser();
    GreenCardController controller = new GreenCardController();

    //Act
    ActionResult<AppUser> actionResult = controller.UpdateArgosUser(expected);
    CreatedAtRouteResult result = actionResult.Result as CreatedAtRouteResult;
    AppUser actual = result.Value as AppUser;

    //Assert
    Assert.AreEqual(expected, actual);
}