Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Ahmed Abdul Moniem 4 posts 54 karma points
    May 26, 2014 @ 13:47
    Ahmed Abdul Moniem
    0

    ApplicationContext.Current is always null while I am trying to write my integration tests.

    Dear All,

    Now I am trying to create my integration tests on my system.

    For example:

    I would like to insert a member to the data base using IMemberService service and then I will check if the member has been inserted or not -> test succeeds.

    When I try to use ApplicationContext.Current in my tests which is written in MS Test and Coded UI frameworks it fails completely because always ApplicationContext.Current is null.

    Any ideas how can I get ApplicationContext.Current running in a UnitTest project or CodedUI project or even dll library without the need to run the website?

  • Ahmed Abdul Moniem 4 posts 54 karma points
    May 27, 2014 @ 08:43
    Ahmed Abdul Moniem
    0

    Any thoughts?

  • Ahmed Abdul Moniem 4 posts 54 karma points
    May 28, 2014 @ 09:27
    Ahmed Abdul Moniem
    100

    OK.

    I found how to do this using Web API

    Here is the Web API

    public class StudentsApiController : UmbracoApiController
    {
        public void AddStudent(Student student)
        {
            IMember newStudent = Services.MemberService.CreateWithIdentity(student.UserName, student.Email, student.Password, "Member");
            newStudent.SetValue("identity", student.Identity);
            newStudent.SetValue("accessCode", student.AccessCode);
            newStudent.SetValue("fullName", student.FullName);
            newStudent.SetValue("nationalId", student.NationalId);
            newStudent.SetValue("gender", student.Gender);
            newStudent.SetValue("mobileNumber", student.MobileNumber);
            newStudent.SetValue("birthDate", student.BirthDate);
            Services.MemberService.AssignRole(student.UserName, "Students");
            Services.MemberService.Save(newStudent);
        }
    
        [HttpPost]
        public void DeleteStudent([FromBodystring userName)
        {
            Services.MemberService.Delete(Services.MemberService.GetByUsername(userName));
        }
    
        public int GetAllStudentsCount()
        {
            return Services.MemberService.GetCount(MemberCountType.All);
        }
    
        public bool GetEmailExistenceStatus(string email)
        {
            return Services.MemberService.GetByEmail(email) != null;
        }
    
        public Student GetStudentByEmail(string email)
        {
            IMember member = Services.MemberService.GetByEmail(email);
    
            if (member == null)
            {
                return null;
            }
    
            Student student = new Student
            {
                UserName = member.Username,
                FullName = member.GetValue("fullName").ToString(),
                NationalId = member.GetValue("nationalId").ToString(),
                Gender = member.GetValue("gender").ToString(),
                MobileNumber = member.GetValue("mobileNumber").ToString(),
                BirthDate = DateTime.Parse(member.GetValue("birthDate").ToString())
            };
    
            return student;
        }
    
        public Student GetStudentById(int studentId)
        {
            IMember member = Services.MemberService.GetById(studentId);
    
            if (member == null)
            {
                return null;
            }
    
            Student student = new Student
            {
                UserName = member.Username,
                FullName = member.GetValue("fullName").ToString(),
                NationalId = member.GetValue("nationalId").ToString(),
                Gender = member.GetValue("gender").ToString(),
                MobileNumber = member.GetValue("mobileNumber").ToString(),
                BirthDate = DateTime.Parse(member.GetValue("birthDate").ToString())
            };
    
            return student;
        }
    
        public Student GetStudentByUserName(string userName)
        {
            IMember member = Services.MemberService.GetByUsername(userName);
    
            if (member == null)
            {
                return null;
            }
    
            Student student = new Student
            {
                UserName = member.Username,
                FullName = member.GetValue("fullName").ToString(),
                NationalId = member.GetValue("nationalId").ToString(),
                Gender = member.GetValue("gender").ToString(),
                MobileNumber = member.GetValue("mobileNumber").ToString(),
                BirthDate = DateTime.Parse(member.GetValue("birthDate").ToString())
            };
    
            return student;
        }
    
        public bool GetUserNameExistenceStatus(string userName)
        {
            return Services.MemberService.Exists(userName);
        }
    
        public void UpdateStudent(Student student)
        {
            IMember member = Services.MemberService.GetByUsername(student.UserName);
            if (member == null)
            {
                throw new InvalidOperationException("No such student in database.");
            }
            member.SetValue("identity", student.Identity);
            member.SetValue("accessCode", student.AccessCode);
            member.SetValue("fullName", student.FullName);
            member.SetValue("nationalId", student.NationalId);
            member.SetValue("gender", student.Gender);
            member.SetValue("mobileNumber", student.MobileNumber);
            member.SetValue("birthDate", student.BirthDate);
            Services.MemberService.Save(member);
        }
    }

     

    And here is the Consumer of the Web API

    public class MembersIntegrationTestsHelper
    {
        private const string ApplicationUrl = "http://localhost:1534/";
    
        public static void AddStudent(Student student)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.PostAsJsonAsync("Umbraco/Api/StudentsApi/AddStudent", student).Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
            }
        }
    
        public static void DeleteStudent(string userName)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.PostAsJsonAsync("Umbraco/Api/StudentsApi/DeleteStudent", userName).Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
            }
        }
    
        public static int GetAllStudentsCount()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.GetAsync("Umbraco/Api/StudentsApi/GetAllStudentsCount").Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
    
                return int.Parse(response.Content.ReadAsStringAsync().Result);
            }
        }
    
        public static Student GetStudentByEmail(string email)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.GetAsync("Umbraco/Api/StudentsApi/GetStudentByEmail?email=" + email).Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
    
                return response.Content.ReadAsAsync<Student>().Result;
            }
        }
    
        public static Student GetStudentById(int studentId)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.GetAsync("Umbraco/Api/StudentsApi/GetStudentById?studentId=" + studentId).Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
    
                return response.Content.ReadAsAsync<Student>().Result;
            }
        }
    
        public static Student GetStudentByUserName(string userName)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.GetAsync("Umbraco/Api/StudentsApi/GetStudentByUserName?userName=" + userName).Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
    
                return response.Content.ReadAsAsync<Student>().Result;
            }
        }
    
        public static bool IsEmailExists(string email)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.GetAsync("Umbraco/Api/StudentsApi/GetEmailExistenceStatus?email=" + email).Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
    
                return bool.Parse(response.Content.ReadAsStringAsync().Result);
            }
        }
    
        public static bool IsUserNameExists(string userName)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.GetAsync("Umbraco/Api/StudentsApi/GetUserNameExistenceStatus?userName=" + userName).Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
    
                return bool.Parse(response.Content.ReadAsStringAsync().Result);
            }
        }
    
        public static void UpdateStudent(Student student)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ApplicationUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = client.PostAsJsonAsync("Umbraco/Api/StudentsApi/UpdateStudent", student).Result;
                if (!response.IsSuccessStatusCode)
                    throw new Exception(
                        "Error happened. Check the response data.");
            }
        }
    }

     

    Then I can use the consumer directly from any class in my tests like this:

    Student oldStudent = new Student
                {
                    UserName = userName,
                    Password = "123456",
                    Gender = "M",
                    FullName = "حسن محمد",
                    Email = email,
                    NationalId = "0123456789",
                    BirthDate = DateTime.Now.AddYears(-1),
                    MobileNumber = "966123456789"
                };
    
    MembersIntegrationTestsHelper.AddStudent(oldStudent);

    // Complete the rest of my integration test ... 
  • Ahmed Abdul Moniem 4 posts 54 karma points
    May 28, 2014 @ 09:29
    Ahmed Abdul Moniem
    0

    Please, if any administrator can solve the coloring issue of the code. This would be nice. Thanks.

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies