skip to Main Content

Here is the method that I am going to test and I want IsPhoneNomValid() would return false so then I would be able to assert my expectations:

public async Task<UserResponseDto> RegisterUser(RegistrationRequestDto register, CancellationToken cancelationToken)
    {
        // I want the IsPhoneNomValid() method, Would return "FALSE"
        var isPhoneNumberValid = register.PhoneNumber.IsPhoneNomValid();

        if (!isPhoneNumberValid)
            return new UserResponseDto
            {
                Status = new StatusMaker().ErrorStatus("Some Error Message")
            };

        var isActiveAccountPhoneNumberExists = await IsActiveAccountPhoneNumberExist(register.PhoneNumber, cancelationToken);


        if (isActiveAccountPhoneNumberExists.Status == "error")
            return new UserResponseDto
            {
                Status = isActiveAccountPhoneNumberExists
            };

       

    }

RegisterUser_MustReturnPhoneNumberError is my Test method:

public class AccountUserTests
{

    private Mock<IUserService> _userService { get; set; }

    public AccountUserTests()
    {
        _userService = new Mock<IUserService>();
    }

    public async Task RegisterUser_MustReturnPhoneNumberError()
    {
        //Arrang

        // in here I want to setup IsPhoneNomValid() would return false.

        //Act

        //Assert
    }
}

Is there any way that I can test the static methods which are used in my main function which I am testing ?

Here is the IsPhoneNomValid() codes:

public static class Validation
{
    public static bool IsPhoneNomValid(this string phoneNumber)
    {
        //TODO Does it need to be foreign phone numbers ?
        var isMatch = Regex.Match(phoneNumber, @"^09[0-9]{9}$");

        if (isMatch.Success)
            return true;

        return false;
    }
}

2

Answers


  1. You want to test your static method IsPhoneNomValid.

        [Theory]
        [InlineData("123456789")]
        public void TestMethod(string phoneNumber)
        {
            bool isPhoneNumber =Validation.IsPhoneNomValid(phoneNumber);
            Assert.True(isPhoneNumber);
        }
    

    With InlineData, you can test with multiple phone numbers.

    Login or Signup to reply.
  2. The best option is to use a really invalid phone number in your case. But I have a lib SMock that can do what you want. Here is an example of usage:

    public async Task RegisterUser_MustReturnPhoneNumberError()
    {
        Mock.Setup(context => Validation.IsPhoneNomValid(context.It.IsAny<string>()), async () =>
        {
            // You must test RegisterUser method in this scope
            // Here Validation.IsPhoneNomValid will always return false
            var result = await RegisterUser(register, ct);
            Assert.AreEqual(expectedStatus, result.Status);
        }).Returns(false);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search