Random Test Code

Manage Time, Software, and Business, Easily


6 November 2021 by jr101dallas

⇠ Back to Posts

Now I Know

I learned that the random number generator seed really does control the numbers generated, so now it’s time to fix my test. I’m going to have to fiddle around a bit to get things the way I need them, but it should be a reasonably easy thing I think.

Planting the Seed

Actually.. I looked into the Target code and saw almost immediately an easy way into what I need to do. I hadn’t really figured it out before but a second constructor for Target that takes a Random will work out perfectly.

        private Random _rand;

        public Target(Universe unv)
        {
            _unv = unv;
            _rand = new Random();
        }
        
        public Target(Universe unv, Random rng)
        {
            _unv = unv;
            _rand = rng;
        }

Oh yeah, except, I’ve got the systems generating automatically from Infrastructure and that’s generating automatically as part of Universe. That basically means this code right now.

        private Random _rand;
        public Infrastructure inf;

        public Universe() : this(new Random()){}  

        public Universe(Random rng)
        {
            _rand = rng;
            inf = new Infrastructure(this, _rand);
        }

        public Infrastructure(Universe unv, Random rng)
        {
            _unv = unv;
            target = new Target(_unv, rng);
        }

And then the test is still really easy, like this.

        [TestMethod]
        public void TargetEntityRemovedFromPlay()
        {
            var rng100 = new Random(100);            
            var unv = new Universe(rng100);
            var originEntity = unv.GetEntity();
            var targetEntity = unv.GetEntity();
            var tEntityId = targetEntity.Id;

            unv.inf.target.TargetEntity(originEntity, targetEntity);

            Assert.IsFalse(unv.entities.TryGetValue(tEntityId, out _), "Targeted Entity still exists.");
        }

Random Everywhere

I’m trying to decide how much I object to the Random instance getting handed around everywhere. I sort of object, but this setup will also support the thoughts I was having about fun with actually sharing and user configurable seed values. I’ll keep going for now and see if I get cranky with it later.

tags: code - testing - random - seed

⇠ Testing Random

Inventory ⇢