AutoFixture - configure fixture to limit string generation length

后端 未结 7 1156
长情又很酷
长情又很酷 2020-12-13 17:44

When using autofixture Build method for some type, how can I limit the length of the strings generated to fill that objects string properties/fields?

7条回答
  •  醉话见心
    2020-12-13 17:59

    Here's a specimen builder that can generate random strings of arbitrary length - even longer than the Guid+PropertyName strings that are by default. Also, you can choose the subset of chars you want to use and even pass in your own random (so that you can control the seed if you need to)

    public class RandomStringOfLengthRequest
    {
        public RandomStringOfLengthRequest(int length) : this(length, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890 !?,.-")
        {
        }
    
        public RandomStringOfLengthRequest(int length, string charactersToUse): this(length, charactersToUse, new Random())
        {
        }
    
        public RandomStringOfLengthRequest(int length, string charactersToUse, Random random)
        {
            Length = length;
            Random = random;
            CharactersToUse = charactersToUse;
        }
    
        public int Length { get; private set; }
        public Random Random { get; private set; }
        public string CharactersToUse { get; private set; }
    
        public string GetRandomChar()
        {
            return CharactersToUse[Random.Next(CharactersToUse.Length)].ToString();
        }
    }
    
    public class RandomStringOfLengthGenerator : ISpecimenBuilder
    {
        public object Create(object request, ISpecimenContext context)
        {
            if (request == null)
                return new NoSpecimen();
    
            var stringOfLengthRequest = request as RandomStringOfLengthRequest;
            if (stringOfLengthRequest == null)
                return new NoSpecimen();
    
            var sb = new StringBuilder();
            for (var i = 0; i < stringOfLengthRequest.Length; i++)
                sb.Append(stringOfLengthRequest.GetRandomChar());
    
            return sb.ToString();
        }
    }
    

    You then can use it to populate a property of an object like this:

            var input = _fixture.Build()
                                .With(x => x.AccountNumber,
                                      new SpecimenContext(new RandomStringOfLengthGenerator())
                                          .Resolve(new RandomStringOfLengthRequest(50)))
                                .Create();
    

提交回复
热议问题