Should unit tests be declared inline?

I have long been a fan of the Python doctest library for the simple reason that comments can be useful not only, but also applicable in the statement of the correct behavior. I recently came across a (apparently) little-known System.Diagnostics.ConditionalAttribute for .NET. This can be easily used so that you can define tests for your class methods inside the class itself. Here is a simple example:

using System.Diagnostics;
using NUnit.Framework;

namespace ClassLibrary1
{
    public class Class1
    {
        public static int AddTwoNumbers(int x, int y)
        {
            return x + y;
        }

        [Conditional("DEBUG")]
        [TestCase(1, 1, 2)]
        [TestCase(1, 2, 3)]
        [TestCase(2, 1, 3)]
        [TestCase(11, 7, 18)]
        public static void TestAddTwoNumbers(int x, int y, int sum)
        {
            int actual = AddTwoNumbers(x, y);
            Assert.AreEqual(sum, actual);
        }
    }
}

By doing this, you can create a debug assembly that will run the tests and the production assembly with all its removal, similar to how FAKE can create projects . The question is, should you? Is this a good practice? Why or why not?

, , . , . , ?

+3
4

ConditionalAttribute , . , .

, Debug.WriteLine Conditional("DEBUG"), . , , Debug.WriteLine, DEBUG.

, :

#if DEBUG
...
#endif

, . . , , . ( , , , .)

. , , - , , , . , , DEBUG ... , ? , , .

+4

(IMO) .

Debug , , ( DEBUG ) , , ( , ).

, , . , , .

, , , .

- . ( ..), ?

+2

.

, . , . , . , ( - , ), , , , InternalsVisibleTo.

, . , . , , . " ". , . . , . , .

. , , , , . . .

+2

: . , , ConditionalAttribute: , , .

, , . , . Debug, Release, . VS, - .

, CC . , Debug ( ) Release ( , dll, ).

Please note that code contracts do not replace unit testing, but this is a nice addition to it.

0
source

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


All Articles