vendredi 30 décembre 2016

How to pass UserIdentity from test in unit testing

I'm trying to write test cases for my web api methods.

 [Fact]
 public async Task Get_Message_By_Id()
 {
    var messages = new Messages()
    {
        MessageId = 1,
        Recipient = "1;2;3",
        Subject = "Test Subject",
        MessageText = "test subject"
    };

    var mesBL = new Mock<IMessagesBusinessLogic>();
        mesBL
            .Setup(repo => repo.GetRecivedMessageById(It.IsAny<IWebToken>() ,messages.MessageId))
            .Returns(Task.FromResult(messages));

    var messageController = new MessagesController(mesBL.Object);

    var contentResult = await messageController.GetRecivedMessageById(messages.MessageId) as OkObjectResult; 

    Assert.NotNull(contentResult);
 }

I get an error of null reference while GetRecivedMessageById method call.

Controller method;

[HttpGet]
[Route("{id:int}")]
public async Task<IActionResult> GetRecivedMessageById(int id)
{
    return Ok(await _messagesBusinessLogic.GetRecivedMessageById(User.GetWebToken(), id));
}

Here, issue is because, user identity passing NULL.

GetWebToken():

public static IWebToken GetWebToken(this ClaimsPrincipal principal)
{
    var identity = principal.Identity as UserIdentity;
    if (identity == null)
        throw new InvalidOperationException(" ");

    return identity.WebToken;
}

How can we pass it from Test?

Aucun commentaire:

Enregistrer un commentaire