Skip to content

Instantly share code, notes, and snippets.

@configurator
Created October 10, 2014 00:32
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 configurator/1bc52b0ba127aed03a71 to your computer and use it in GitHub Desktop.
Save configurator/1bc52b0ba127aed03a71 to your computer and use it in GitHub Desktop.
100% test coverage is easy. Making it useful is practically impossible.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Misadonet.Server.Test {
class UltimateTestCase {
public void Run() {
foreach (var type in (from file in GetAllFiles()
let assembly = TryLoadAssembly(file)
where assembly != null
from type in assembly.GetTypes()
select type)) {
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
Test(method, null);
}
foreach (var method in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static)) {
Test(method, null);
}
foreach (var instance in from constructor in type.GetConstructors()
let instance = TryConstruct(constructor, type)
where instance != null
select instance) {
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)) {
Test(method, instance);
}
foreach (var method in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)) {
Test(method, instance);
}
}
}
}
private void Test(MethodInfo method, object instance) {
try {
method.Invoke(instance, (from param in method.GetParameters()
select GetValue(param.ParameterType)).ToArray());
} catch { }
}
private static IEnumerable<string> GetAllFiles() {
return Directory.GetFiles(".", "*.dll")
.Concat(Directory.GetFiles(".", "*.exe"));
}
private Assembly TryLoadAssembly(string file) {
try {
return Assembly.LoadFrom(file);
} catch {
return null;
}
}
private object TryConstruct(ConstructorInfo constructor, Type type) {
try {
return constructor.Invoke((from param in constructor.GetParameters()
select GetValue(param.ParameterType)).ToArray());
} catch {
return GetValue(type);
}
}
private object GetValue(Type type) {
try {
return Activator.CreateInstance(type);
} catch {
// Activator.CreateInstance() will fail for reference types which don't have default
// constructors, or when the default constructor throws. It will never fail for a
// value type, so null is a sensible value here.
return null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment