Unit Testing . net MVC - Httpcontext Problem

Asked

Viewed 52 times

0

Good afternoon,

I have the following application as Solution:

Controller:

public ActionResult Index()
    {

        string username = HttpContext.Current.Request.LogonUserIdentity.Name;

        UtilizadorDbo utilizadorDbo = new UtilizadorDbo();
        ViewBag.userLogon = utilizadorDbo.getUtilizador(util.getClientUser(username)).nome;

        ViewBag.dataPT = util.getDatetimePT();

        return View();
    }

Whereas in the unitary test I have the following:

[TestClass]
public class HomeControllerTest
{

    [TestMethod]
    public void Index()
    {
        // Arrange
        HomeController controller = new HomeController();
        // Act
        ViewResult result = controller.Index() as ViewResult;
        // Assert
        Assert.IsNotNull(result);
    }

}

But every time I try to run the test, this fails by indicating System.Nullreferenceexception: Object Reference not set to an instance of an Object. Pointing to the reference line Httpcontext.Current.Request.LogonUserIdentity.Name;

I read that I should do a Context Mock, but I don’t know how to do it, someone can help me?

Regards

  • That is . NET Core?

  • I’m using . NET MVC

  • There is no . NET MVC. What I wanted to ask is which framework you are using: . NET Framework, . NET Core or . NET 5...

  • Using . NET Framework

  • 1

    arrow the HttpContext.Current in the test, so: HttpContext.Current = new HttpContext(... passe os parametros....)

  • Did you manage to evolouir there?

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.