Created
October 10, 2014 00:32
-
-
Save configurator/1bc52b0ba127aed03a71 to your computer and use it in GitHub Desktop.
100% test coverage is easy. Making it useful is practically impossible.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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