0

I have a function which contains validation that check whether a variable value is null or not. I want to test that class method using xunit test. But due to this validation, I failed to call the Unit Test.

Class

public interface ICountry<CountryModel>
    {
        Task ProcessCall(IList<string> countryCodes);
    }
    public class CallOptions
    {
        public string Name { get; set; }
    }
  
    public class Country<CountryModel> : ICountry<CountryModel>
    {
        
        private readonly CallOptions _options;
        private readonly Irepo _repo;

        public Country(IOptions<CountryModel> options,Irepo repo)
        {         _repo= repo
            _options = options.Value;

            if (string.IsNullOrWhiteSpace(_options.Name))
            {
                throw new ArgumentException("Missing  name");
            }
        }

        public async Task ProcessCall(IList<string> Codes)
        {
           _repo.set(Codes);
        }

Unit Test

public class ProcessorTests 
{
    private  Mock<Irepo> _RepositoryMock;
    private Mock<IOptions<CallOptions>> options;

    public ProcessorTests()
    {
        _RepositoryMock = new Mock<Irepo>();
        options = new Mock<IOptions<CallOptions>>();
        options.SetReturnsDefault("test");    

}

private Country<CountryModel> CreateSut()
    {
        return new Country<CountryModel>(_RepositoryMock.Object, _options.Object);
    }
    
  


    [Fact]
    public async Task ShouldCheck()
    {
        GetRepoMock();
        await CreateSut().ProcessCall(new string[] { "TEST" });

        _RepositoryMock.Verify(x => x.set(It.IsAny<List<string>>()), Times.Once);
    }
  private void GetRepoMock()
    {
        _RepositoryMock
            .Setup(m => m.set(It.IsAny<List<string>>())
            .ReturnsAsync(new Response<Code>(false, null, Enumerable.Empty<Code>()));
    }

But when the unit test executes, the value of _options.Name is empty and failed the test while called the Country method. Any idea regarding this?

amd
  • 11
  • 3
  • It appears that the mocked options that you're passing in does not have any value set for the Name property. If you're passing in a POCO (such as options), it would be better to just create a new instance of it rather than set up a mock. A mock is really meant to provide expected output for what normally would have been logic or external calls, but there is no logic in your options, you are simply retrieving a value stored on a property. If you want to keep the mock, you need to mock the Get https://stackoverflow.com/questions/12141799/moq-setupget-mocking-a-property – emagers Jun 21 '22 at 15:50
  • how to set any value for the Name property – amd Jun 21 '22 at 17:15
  • CallOptions tr = new CallOptions(); tr.Name = "test"; options = new Mock>(new IOptions()); – amd Jun 21 '22 at 17:36

0 Answers0