Unit Testing with functions that return random results

后端 未结 11 1928
太阳男子
太阳男子 2020-12-05 01:25

I don\'t think that this is specific to a language or framework, but I am using xUnit.net and C#.

I have a function that returns a random date in a certain range. I

11条回答
  •  既然无缘
    2020-12-05 02:16

    Mock or fake out the random number generator

    Do something like this... I didn't compile it so there might be a few syntax errors.

    public interface IRandomGenerator
    {
        double Generate(double max);
    }
    
    public class SomethingThatUsesRandom
    {
        private readonly IRandomGenerator _generator;
    
        private class DefaultRandom : IRandomGenerator
        {
            public double Generate(double max)
            {
                return (new Random()).Next(max);
            }
        }
    
        public SomethingThatUsesRandom(IRandomGenerator generator)
        {
            _generator = generator;
        }
    
        public SomethingThatUsesRandom() : this(new DefaultRandom())
        {}
    
        public double MethodThatUsesRandom()
        {
            return _generator.Generate(40.0);
        }
    }
    

    In your test, just fake or mock out the IRandomGenerator to return something canned.

提交回复
热议问题