Как установить некоторые свойства и оставить другие значения по умолчанию, используя AutoFixture и AutoMoqCustomization? - PullRequest
0 голосов
/ 18 марта 2020

Я новичок в AutoFixture , поэтому я надеюсь, что вы можете помочь. Как установить некоторые свойства в объекте, но оставить другие в качестве значения по умолчанию для AutoFixture - при использовании атрибута [Theory] в XUnit и атрибута AutoDataAttribute .

Например, в нижеприведенном изобретенном Аэропорту примере на основе курса Pluralight's Джейсона Роберта при настройке свойства (или объекта Аэропорт), например,

f.Customize<Mock<IAirport>>(c => c.Do(m => m.SetupGet(i => i.code).Returns("NOO")));

другой свойства часто бывают нулевыми, или я должен установить их вручную, а не позволить AutoFixture делать это. Я бы предпочел иметь более чистый код, в котором fixtureFactory устанавливает все свойства для Аэропорта, чтобы тестирование модуля V2 проходило только с одним параметром Airport.

Итак, в рамках fixtureFactory

  • Как установить свойства MULTIPLE?
  • Как использовать значения AutoFixture по умолчанию вместо того, чтобы оставить неинициализированные значения равными NULL?

Спасибо!

using AutoFixture;
using AutoFixture.AutoMoq;
using AutoFixture.Xunit2;
using Moq;
using System;
using Xunit;
namespace AirportTesterWithAutoFixture
{
    public interface IAirport
    {
        string city { get; set; }
        string code { get; set; }
        string country { get; set; }
        string name { get; set; }

        void CallAirTrafficControl();
    }
    public class Airport : IAirport
    {
        public string name { get; set; }
        public string city { get; set; }
        public string code { get; set; }
        public string country { get; set; }
        public Airport()
        {
        }
        public Airport(string name, string code, string country, string city)
        {
            this.name = name;
            this.code = code;
            this.country = country;
            this.city = city;
        }
        public void CallAirTrafficControl()
        {
            if (this.country.Equals("Canada") && this.code.StartsWith("Y"))
            {
                // Send "Bonjour!"();
            }
            else
            {
                throw new Exception("Invalid code for Canada");
            }
        }
    }
    public class UnitTest1
    {
        [Fact]
        public void V1_Validate_ExceptionThrown_ForInvalidCanadianAirportCode()
        {
            var fixture = new Fixture();
            var sut = fixture.Create<Airport>();
            // Overwrite code and country with invalid setting for Canada.
            sut.country = "Canada";
            sut.code = "NOT";
            Assert.ThrowsAny<Exception>(() => sut.CallAirTrafficControl());
        }
        [Theory]
        [AutoMoqInvalidAirportDataAttribute]
        public void V2_Validate_ExceptionThrown_ForInvalidCanadianAirportCode(IAirport sut, string name, string city)
        {
            Airport airport = new Airport(name, sut.code, sut.country, city);
            Assert.ThrowsAny<Exception>(() => airport.CallAirTrafficControl());
        }
    }
    // https://stackoverflow.com/questions/58998834/how-to-use-ifixture-buildt-with-automoqcustomization-when-t-is-an-interface
    public class AutoMoqInvalidAirportDataAttribute : AutoDataAttribute
    {
        public static Func<IFixture> fixtureFactory = () =>
        {
            IFixture f = new Fixture().Customize(new AutoMoqCustomization());
            f.RepeatCount = 5;
    // How do you set MULTIPLE properties?
    // How does one use the default AutoFixture values rather than leaving the uninitialized values as null?
    // Can one pass a custom property used earlier in the Fixture creation process to another custom property used later?
    f.Customize<Mock<IAirport>>(c => c.Do(m => m.SetupGet(i => i.code).Returns("NOT")));
            return f;
        };
        public AutoMoqInvalidAirportDataAttribute() : base(fixtureFactory)
        {
        }
    }
}

1 Ответ

0 голосов
/ 31 марта 2020

AutoFixture не заполняет фиктивные свойства по умолчанию, но это можно сделать. Эти сообщения в блоге описывают, как это сделать:

https://blog.ploeh.dk/2013/04/05/how-to-configure-automoq-to-set-up-all-properties/

https://blog.ploeh.dk/2013/04/08/how-to-automatically-populate-properties-with-automoq/

Автор AutoFixture не однако рекомендую этот подход, так как он считает объявление свойств в интерфейсах запахом дизайна. К сожалению, я не смог найти оригинальное обсуждение этой топи c, но оно спрятано где-то на StackOverflow в комментариях. Может быть, вы сможете найти его, если вы go через профиль Марка Seemann.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...