I've just started programming in C# Webforms (previous experience in VB Webforms) and I am producing a web app that will be a small part of a bigger project.
I have created 3 separate projects, one for the webforms, one for the class library and one for the tests.
I have added all the projects into one solution and added appropriate references, Both the Webforms and Tests projects reference the class library.
I have a class in the class library that finds the username of the logged in user:
public class LoggedInUser
{
public string UserName
{
get { return HttpContext.Current.User.Identity.Name; }
}
}
In the page load event of one of my pages, I use this class to set the text property of a literal to display the name on the screen.
protected void Page_Load(object sender, EventArgs e)
{
LoggedInUser CurrentUser = new LoggedInUser();
LitUser.Text = string.Format(" {0}", CurrentUser.UserName);
}
This works fine.
To be complete I thought I would write a unit test to make sure the logged in username is what I expected.
[TestMethod]
public void Test_Logged_In_User_Name()
{
LoggedInUser actualUser = new LoggedInUser();
string expectedUserName = "myUserName";
string actualUserName = actualUser.UserName;
Assert.AreEqual(expectedUserName, actualUserName);
}
When I run the test it throws the following exception:
System.NullReferenceException: Object reference not set to an instance of an object
on this line:
get { return HttpContext.Current.User.Identity.Name; }
Any thoughts would as always be greatly appreciated.