问题
Are there any technologies I can use to find all tests in a solution that are annotated as a test ([TestMethod]
, [Fact]
, [Theory]
...)?
Context: I am quite new to all this but attempting to iron out a continuous deployment strategy. I want to find and run all tests in a solution during/following a release process. These are not build dependent unit tests, these are part of end to end solution tests.
Please let me know if my thinking is away from the right track.
回答1:
So if you want a tool that just gathers methods with the TestAttribute, Visual Studio has that built in. It's the Test Explorer, which examines the assemblies in your solution and digs out tests based on the attributes, then lets you run them. It's available in some versions of VS (I use Professional, which has it); I'm not sure exactly which ones do, though.
Usually apps written for this purpose are the way to go. However, you could scan your assemblies yourself for these attributes. It's not really necessary here -- as I said there are testing tools out here that can do that, and things like VSTS will help you integrate into a deployment process -- but since you mentioned you're new to all of this I'll leave it here as something you may or may not need to use in the future. If nothing else, you can adapt it to something else.
Basically, you can use Reflection to get your assemblies, classes, methods, etc. and you can get the attributes that decorate each of them. You'd do it like this:
[TestClass]
public class AttributeFinder
{
[TestMethod]
public void MyTestMethod()
{
// Do something
}
public static void FindAttributes()
{
var assembly = Assembly.GetAssembly(typeof(AttributeFinder));
var types = assembly.GetTypes();
foreach (var t in types)
{
var typeAttr = t.GetCustomAttribute(typeof(TestClassAttribute));
if (typeAttr != null)
{
// Your class has a TestClass attribute on it!
}
var methods = t.GetMethods();
foreach (var m in methods)
{
var methodAttr = m.GetCustomAttribute(typeof(TestMethodAttribute));
if (methodAttr != null)
{
// This method has the TestMethod attribute!
}
}
}
}
}
Again, there are tools that do this for you automatically, and QHero provided you some links. What I've presented here is the long way around and would require you writing your own tooling, which isn't necessary with the stuff out there. But Reflection is a handy technique to know, and this might be useful to, say, generate a report outside of testing tools that lists your test methods/classes or something.
回答2:
What kind of technologies are you going to use ? Not sure I understand very well your request but if you plan to use .NET Unit test you can have a look here: https://docs.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing
Or you can use also the famous NUnit, https://stackoverflow.com/questions/43007761/how-to-run-nunit-tests-in-visual-studio-2017
来源:https://stackoverflow.com/questions/45942674/c-sharp-find-all-tests-in-a-solution