From fc6ac7ad101347ec096f892820750b9ce65f1837 Mon Sep 17 00:00:00 2001 From: choutianxius Date: Fri, 13 Sep 2024 09:32:22 -0500 Subject: [PATCH] #24: Implement CreateApplicant unit test for good inputs --- .../Services/ApplicantServiceTest.cs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/AggieRent.Tests/Services/ApplicantServiceTest.cs b/AggieRent.Tests/Services/ApplicantServiceTest.cs index 823dc6c..3a2d87f 100644 --- a/AggieRent.Tests/Services/ApplicantServiceTest.cs +++ b/AggieRent.Tests/Services/ApplicantServiceTest.cs @@ -1,6 +1,7 @@ using AggieRent.DataAccess; using AggieRent.Models; using AggieRent.Services; +using Microsoft.AspNetCore.Mvc; using Moq; using Xunit; @@ -89,4 +90,64 @@ public void GetApplicants_ThenOk() mockApplicantRepository.Verify(x => x.GetAll(), Times.Once()); } } + + public class ApplicantService_CreateApplicantShould + { + [Fact] + public void CreateApplicant_GoodInput_ThenAddApplicantAndReturnId() + { + var mockApplicantRepository = new Mock(); + List applicants = + [ + new() + { + Id = Guid.NewGuid().ToString(), + Email = "aggie@tamu.edu", + HashedPassword = BC.HashPassword("veryStr0ngP@ssw0rd"), + FirstName = "John", + LastName = "Doe", + }, + ]; + mockApplicantRepository.Setup(x => x.GetAll()).Returns(applicants.AsQueryable()); + mockApplicantRepository + .Setup(x => x.Add(It.IsAny())) + .Callback( + (Applicant a) => + { + if (applicants.FirstOrDefault(a1 => a1.Id == a.Id) != null) + throw new Exception("Duplicate ID"); + applicants.Add(a); + } + ); + var applicantService = new ApplicantService(mockApplicantRepository.Object); + + var email = "aggie1@tamu.edu"; + var password = "superStr0ngp@ssw0rd"; + var firstName = "John"; + var lastName = "Deer"; + var gender = Gender.Female; + var birthday = new DateOnly(2000, 1, 1); + var description = "Hi I'm John Deer"; + var id = applicantService.CreateApplicant( + email, + password, + firstName, + lastName, + gender, + birthday, + description + ); + + Assert.Equal(2, applicants.Count); + var createdApplicant = applicants.FirstOrDefault(a => a.Id == id); + Assert.NotNull(createdApplicant); + Assert.Equal(email, createdApplicant.Email); + Assert.True(BC.Verify(password, createdApplicant.HashedPassword)); + Assert.Equal(firstName, createdApplicant.FirstName); + Assert.Equal(lastName, createdApplicant.LastName); + Assert.Equal(gender, createdApplicant.Gender); + Assert.Equivalent(new DateOnly(2000, 1, 1), createdApplicant.Birthday); + Assert.Equal(description, createdApplicant.Description); + } + } }