Skip to content

Instantly share code, notes, and snippets.

@giginet
Last active May 28, 2017 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giginet/9b29499f2eed8f63b030c9498459b1b5 to your computer and use it in GitHub Desktop.
Save giginet/9b29499f2eed8f63b030c9498459b1b5 to your computer and use it in GitHub Desktop.
UnityMoqTesting
using System.Collections.Generic;
using UnityEngine;
public interface IRandomGenerator
{
float GenerateValue();
int GenerateInteger(int min, int max);
}
internal class UnityRandomGenerator: IRandomGenerator {
public float GenerateValue()
{
return Random.value;
}
public int GenerateInteger(int min, int max)
{
return Random.Range(min, max);
}
}
public class RandomUtils {
private static RandomUtils instance = null;
public static RandomUtils Instance
{
get {
if (instance == null)
{
instance = new RandomUtils();
}
return instance;
}
}
private readonly IRandomGenerator generator = null;
public RandomUtils(IRandomGenerator generator)
{
this.generator = generator;
}
internal RandomUtils()
{
generator = new UnityRandomGenerator();
}
public T Choice<T>(IList<T> list)
{
var index = generator.GenerateInteger(0, list.Count - 1);
return list[index];
}
}
using UnityEngine;
using System.Collections.Generic;
using NUnit.Framework;
using Moq;
public class RandomUtilsTests {
[Test]
public void TestChoice()
{
var generator = new Mock<IRandomGenerator>();
generator.Setup(m => m.GenerateInteger(It.Is<int>(i => i == 0), It.Is<int>(i => i == 3))).Returns(1);
var list = new List<int> { 1, 4, 9, 16 };
var utils = new RandomUtils(generator.Object);
Assert.AreEqual(utils.Choice(list), 4);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment