NUnit Attributes

I use NUnit and apply a category attribute to some of my tests:

[Category("FastTest")] 

These are tests that must be run very quickly, in less than 10 seconds. so I also decorate them

 [Timeout(10000)] 

And now the question is:

How can I do this every time I decorate the [Category ("FastTest")] method backstage, will it be automatically issued using [Timeout (1000)] ?

+6
source share
5 answers

Create a live Resharper template that splashes out both attributes, for example, when writing "catfast". Or buy PostSharp and let posthart AOP-decorate all methods marked with the specified category.

+3
source

I do not think this is a very good idea.

  • A category attribute used to group tests, not to set test expectations.
  • How does another developer know that the tests from the FastTest group should run within 10 seconds? Why not 2 seconds? Or maybe 100 milliseconds?
  • You will keep a fixed timeout for all tests in the category. How to set one test for 2 seconds, another for 10 seconds?
  • You will not save much time on this.

Of course you can do it. AOP. Reflection. But the simplest way is to group all the quick tests in one test device and decorate it with the [Timeout] attribute.

+2
source

Create a custom FastTest attribute that inherits from TimeoutAttribute. This attribute would then apply its own category naming convention. Something like this should work

 public class FastTestAttribyte :TimeoutAttribute { protected string categoryName; public FastTestAttribyte (int timeout):base(timeout) { categoryName = "FastTest"; } public string Name { get return categoryName; } } 

Edit

It will work if you decompile an attribute, this is what it does

 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple=true, Inherited=true)] public class CategoryAttribute : Attribute { // Fields protected string categoryName; // Methods protected CategoryAttribute() { this.categoryName = base.GetType().Name; if (this.categoryName.EndsWith("Attribute")) { this.categoryName = this.categoryName.Substring(0, this.categoryName.Length - 9); } } public CategoryAttribute(string name) { this.categoryName = name.Trim(); } // Properties public string Name { get { return this.categoryName; } } } 

I think Nunit will use reflection for the Attribute attribute's Name property.

0
source

I understand what you mean / need, but I do not think this is possible. Do you expect the IDE to add another attribute when adding one or nUnit to find out what a category is and apply some additional attributes for tests of certain categories?

Sounds like a good idea, but in the case it sounds more like a nUnit configuration, rather than a pure C # attribute chain, which I don't know if exists.

0
source

Visual Studio allows you to create custom code snippets that are similar to the Resharper templates described by Marius but cost nothing.

0
source

Source: https://habr.com/ru/post/890600/


All Articles