Skip to content

Instantly share code, notes, and snippets.

@Flayed
Created August 14, 2017 15:04
Show Gist options
  • Select an option

  • Save Flayed/aea484fc48afc272f15061df542cfae6 to your computer and use it in GitHub Desktop.

Select an option

Save Flayed/aea484fc48afc272f15061df542cfae6 to your computer and use it in GitHub Desktop.
Unit Test Base
public class TestBase
{
private readonly ConcurrentDictionary<Type, object> _dependencies = new ConcurrentDictionary<Type, object>();
/// <summary>
/// Gets the substitute matching the provided type from the dependency list
/// </summary>
/// <typeparam name="T">The type of substitute to match</typeparam>
/// <returns>The substitute matching the provided type</returns>
public T GetSubstitute<T>()
{
return (T) GetSubstitute(typeof(T));
}
/// <summary>
/// Gets the substitute matching the provided type from the dependency list
/// </summary>
/// <param name="t">The type of substitute to match</param>
/// <returns>The substitute matching the provided type</returns>
public object GetSubstitute(Type t)
{
object obj;
if (_dependencies.TryGetValue(t, out obj))
return obj;
obj = AddDependency(t);
if (obj == null)
throw new NullReferenceException($"{t} was not found in the dependency list");
return obj;
}
/// <summary>
/// Registers an implementation of the provided type with the dependency list
/// </summary>
/// <typeparam name="T">The type to register</typeparam>
/// <param name="instance">The instance of the provided type to register</param>
public void Register<T>(object instance)
{
_dependencies.AddOrUpdate(typeof(T), instance, (k, v) => instance);
}
/// <summary>
/// Creates an instance of the provided type, resolving or creating substitutions for its dependencies from the dependency list.
/// </summary>
/// <typeparam name="T">The type of instance to create</typeparam>
/// <returns>An instance of the provided type</returns>
public T CreateInstance<T>()
{
var ctor = typeof(T).GetConstructors().OrderByDescending(c => c.GetParameters()).FirstOrDefault();
if (ctor == null)
throw new NullReferenceException("Unable to determine the constructor to use");
object[] parameters = ctor.GetParameters().Select(p => GetSubstitute(p.ParameterType)).ToArray();
object instance = ctor.Invoke(parameters.ToArray());
return (T) instance;
}
/// <summary>
/// Adds the dependency to the dependency list
/// </summary>
/// <param name="t">The type to add</param>
/// <returns>The substitute object</returns>
private object AddDependency(Type t)
{
var sub = Substitute.For(new[]{t}, new object[] { });
_dependencies.AddOrUpdate(t, sub, (k, v) => sub);
return sub;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment