asp.net 我怎样才能在我测试的方法中返回一个静态方法的特定值?

dphi5xsq  于 2022-12-15  发布在  .NET
关注(0)|答案(2)|浏览(121)

下面是我将要测试的方法,我希望IsPhoneNomValid()返回false,这样我就可以Assert我的期望值:

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是我的测试方法:

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
    }
}

有什么方法可以测试我正在测试的主函数中使用的静态方法吗?
下面是IsPhoneNomValid()代码:

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;
    }
}
vsikbqxv

vsikbqxv1#

您希望测试静态方法IsPhoneNomValid。

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

使用InlineData,您可以使用多个电话号码进行测试。

eeq64g8w

eeq64g8w2#

最好的选择是在你的情况下使用一个真正无效的电话号码,但是我有一个库SMock可以做你想做的事情,下面是一个用法示例:

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);
}

相关问题