MOQ IConfiguration с конкретными параметрами - PullRequest
0 голосов
/ 25 сентября 2019

Сегодня я писал модульный тест для одного из моих классов с параметром IConfiguration в конструкторе.Я пытался заморозить зависимость и создать sut.

 configuration = builders.Freeze<IConfiguration>();
 apiConfiguration = builders.Create<IAPIConfiguration>();

Когда я запустил тест, я получил исключение, потому что в конструкторе конфигурации API у меня есть строка проверки.

 this.API_KEY = configuration["API:Key"] ?? throw new NoNullAllowedException("API key wasn't found.");

Кажется, что это не издевалось правильно или, по крайней мере, так, как я хотел.Я начинаю задаваться вопросом, есть ли способ макетировать класс IConfiguration с настраиваемыми ключами?

ОБНОВЛЕНО:

SUT:

public class APIConfiguration : IAPIConfiguration
    {
        public APIConfiguration(IConfiguration configuration)
        {
            this.API_KEY = configuration["API:Key"] ?? throw new NoNullAllowedException("API key wasn't found.");
            this._url = configuration["API:URL"] ?? throw new NoNullAllowedException("API key wasn't found.");
        }

        public string API_KEY { get; }

        private string _url
        {
            get { return this._url; }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                    throw new NoNullAllowedException("API url wasn't found.");
                this._url = value;
            }
        }

        public Uri URL
        {
            get
            {
                return this.URL;
            }
            private set
            {
                value = new Uri(this._url);
            }
        }
    }

Тестовый пример:

[TestClass]
    public class UnitTest1
    {

        private readonly IFixture builders;
        private readonly string _apiKey;
        private readonly string _url;
        private readonly IAPIConfiguration apiConfiguration;
        private readonly IConfiguration configuration;

        public UnitTest1()
        {
            builders = new Fixture().Customize(new AutoMoqCustomization());
            _apiKey = builders.Create<string>();
            _url = builders.Create<string>();
            configuration = builders.Freeze<IConfiguration>();
            configuration["API:Key"] = "testKey";
            configuration["API:URL"] = "testUrl";

            apiConfiguration = builders.Build<IAPIConfiguration>().Create();
        }

        [TestMethod]
        public void TestMethod1()
        {
            Assert.AreSame(configuration["API:Key"], apiConfiguration.API_KEY);
        }
    }

Проверка тормозов в конструкторетеста на линии

apiConfiguration = builders.Build<IAPIConfiguration>().Create();

1 Ответ

1 голос
/ 25 сентября 2019

Все, что делает, это создает насмешку.Он ничего не делает при настройке поведения макета.

[TestMethod]
public void TestMethod1() {
    //Arrange
    //Freeze-Build-Create sequence
    var fixture = new Fixture().Customize(new AutoMoqCustomization());
    var apiKey = fixture.Create<string>();
    var url = "http://example.com";
    var configuration = fixture.Freeze<IConfiguration>();

    //Configure the expected behavior of the mock
    var keys = new Dictionary<string, string> {
        { "API:Key" , apiKey },
        { "API:URL", url }
    };
    var mock = Mock.Get(configuration);
    mock.Setup(_ => _[It.IsAny<string>()]).Returns((string key) => keys[key]);

    IAPIConfiguration apiConfiguration = fixture.Build<APIConfiguration>().Create();

    //Act
    var actual = apiConfiguration.API_KEY;

    //Assert
    Assert.AreEqual(apiKey, actual);
    Assert.AreEqual(new Uri(url), apiConfiguration.URL);
}

Вышеизложенное извлекает макет из прибора и настраивает ожидаемое поведение для тестового примера.

Тест также выявил проблемы с объектомтестируется, который должен быть реорганизован до

public class APIConfiguration : IAPIConfiguration {
    public APIConfiguration(IConfiguration configuration) {
        this.API_KEY = configuration["API:Key"] ?? throw new NoNullAllowedException("API key wasn't found.");
        this._url = configuration["API:URL"] ?? throw new NoNullAllowedException("API url wasn't found.");
    }

    public string API_KEY { get; }

    private string _url;

    public Uri URL {
        get {
            return new Uri(this._url);
        }
    }
}

, чтобы исправить проблемы, связанные с его оригинальным дизайном.

...