05 March 2017

Unit Testing the ASP.NET WebForm (Part 1)

Unit testing an ASP.NET Webform gives us more challenging job than a loosely coupled MVC. In practice, we just unit test custom controls and the methods that perform actual logic. In doing so, we try to minimize the code behind and put all those logic in separate libraries or classes.

In my example below, I try to write a unit test (using MSTest) on a method that inserts a new record to the database:


** Test Class **

[TestClass]
class ProfileTests
{
    [TestMethod]
    public void Create_New_Profile_Should_Save_New_Record()
    {
        //Arrange
        var content = new Profile { ProfileId = 1, Name = "Bob", Age = 21m};

        //Act
        var results = ProfileData.Create_New_Profile(content);

        //Assert
        Assert.IsNotNull(results);
    }
}


** Data Model **

public class ProfileData
{
    public static Profile Create_New_Profile(Profile profiles)
    {
        using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ProfileConnectionString"].ConnectionString))
        {
            string strInsert = "INSERT INTO Profile (Name, Age) VALUES(@Name, @Age)";
            var cmd = new SqlCommand(strInsert, con);
            cmd.Parameters.AddWithValue("@Name", profiles.Name);
            cmd.Parameters.AddWithValue("Age", profiles.Age);
            con.Open();
            var profile = new Profile
                {
                    Name = profiles.Name,
                    Age = profiles.Age
                };
            cmd.ExecuteNonQuery();
            con.Close();
            return profile;
        }
    }
}


** Business Model **

public class Profile
{
    public int ProfileId { get; set; }
    public string Name { get; set; }
    public decimal Age { get; set; }



** Code Behind **

protected void btnSave_Click(object sender, EventArgs e)
{
    var profile = new Profile
    {
        Name = txtName.Text,
        Age = Decimal.Parse(txtAge.Text)
    };
    Profiles = ProfileData.Create_New_Profile(profile);
}

No comments:

Post a Comment