如何在C#中对if-else语句进行单元测试?

3

我希望测试if-else语句是否被执行,"if"块从字典/缓存中返回项目并返回输出,而"else"块将输入添加到缓存中并返回一个输出。

IModifyBehavior接口具有一个名为Apply的方法。

我有这些类:

namespace Decorator
{
    using System;

    /// <summary>
    /// Reverse Behavior
    /// </summary>
    public class ReverseBehavior : IModifyBehavior
    {
        /// <summary>
        /// Applies the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>result</returns>
        public string Apply(string value)
        {
            var result = string.Empty;
            if (value != null)
            {
                char[] letters = value.ToCharArray();
                Array.Reverse(letters);
                result = new string(letters); 
            }

            return result; 
        }
    }
}




using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    /// <summary>
    /// Caching Decorator
    /// </summary>
    public class CachingDecorator : IModifyBehavior
    {

        /// <summary>
        /// The behavior
        /// </summary>
        private IModifyBehavior behavior;


        public CachingDecorator(IModifyBehavior behavior)
        {
            if (behavior == null)
            {
                throw new ArgumentNullException("behavior");
            }

            this.behavior = behavior;
        }



        private static Dictionary<string, string> cache = new Dictionary<string, string>();

        /// <summary>
        /// Applies the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>
        /// value
        /// </returns>
        public string Apply(string value)
        {
            ////Key = original value, Value = Reversed
            var result = string.Empty;

            //cache.Add("randel", "lednar");
            if(cache.ContainsKey(value))
            {
                result = cache[value];
            }
            else
            {
                result = this.behavior.Apply(value);// = "reversed";
                ////Note:Add(key,value)
                cache.Add(value, result); 
            }
            return result;
        }
    }
}

这是我目前用于测试的代码,虽然代码能够通过测试,但我不确定我的实现是否正确:

[TestClass]
    public class CachingDecoratorTest
    {
        private IModifyBehavior behavior;

        [TestInitialize]
        public void Setup()
        {
            this.behavior = new CachingDecorator(new ReverseBehavior());
        }

        [TestCleanup]
        public void Teardown()
        {
            this.behavior = null;
        }

        [TestMethod]
        public void Apply_Cached_ReturnsReversedCachedValue()
        {
            string actual = "randel";           
            ////store it inside the cache
            string cached = this.behavior.Apply(actual);

            ////call the function again, to test the else block statement
            ////Implement DRY principle next time
            string expected = this.behavior.Apply(actual);
            Assert.IsTrue(cached.Equals(expected));

        }

        [TestMethod]
        public void Apply_NotCached_ReturnsReversed()
        {
            string actual = "randel";
            string expected = "lednar";
            Assert.AreEqual(expected, this.behavior.Apply(actual));
        }


    }

先生/女士,您的回答将是很有帮助的。谢谢++
3个回答

3

首先,我会分别测试这两个类,进行正确的单元测试。

以下是我如何进行测试。我使用NUnit和Moq(可以在Nuget中获取)作为模拟框架。但您也可以更改测试属性并使用MSTest。

对于反向行为,我涵盖了普通应用程序和应用到空文本的情况:

using System;
using System.Linq;
using Decorator;
using NUnit.Framework;

namespace StackOverflow.Tests.HowToTest
{
    [TestFixture]
    public class ReverseBehaviorTest
    {
        [Test]
        public void Apply()
        {
            const string someText = "someText";
            var target = new ReverseBehavior();
            var result = target.Apply(someText);
            Assert.AreEqual(someText.Reverse(), result);
        }
        [Test]
        public void Apply_WhenNull()
        {
            var target = new ReverseBehavior();
            var result = target.Apply(null);
            Assert.AreEqual(String.Empty, result);
        }
    }
}

对于CachingDecorator,构造函数的异常抛出应用于缓存和不应用于缓存:

using System;
using Decorator;
using Moq;
using NUnit.Framework;

namespace StackOverflow.Tests.HowToTest
{
    [TestFixture]
    public class CachingDecoratorTest
    {
        [Test]
        public void Constructor()
        {
            Assert.Throws(typeof(ArgumentNullException), () => new CachingDecorator(null));
        }

        [Test]
        public void Apply_NotCached()
        {
            var internalBehaviorMock = new Mock<IModifyBehavior>();
            internalBehaviorMock.Setup(x => x.Apply(It.IsAny<string>())).Returns<string>(y => y);
            const string someText = "someText";
            var target = new CachingDecorator(internalBehaviorMock.Object);
            target.Apply(someText);
            internalBehaviorMock.Verify(x => x.Apply(It.IsAny<string>()), Times.Once());
        }

        [Test]
        public void Apply_Cached()
        {
            var internalBehaviorMock = new Mock<IModifyBehavior>();
            internalBehaviorMock.Setup(x => x.Apply(It.IsAny<string>())).Returns<string>(y => y);
            const string someOtherText = "someOtherText";
            var target = new CachingDecorator(internalBehaviorMock.Object);
            target.Apply(someOtherText);
            target.Apply(someOtherText);
            internalBehaviorMock.Verify(x => x.Apply(It.IsAny<string>()), Times.Once());
        }
    }
}

2
最好的方法是使用模拟框架(例如Moq),创建一个虚假的IModifyBehaviour对象。
然后,Apply_NotCached_ReturnsReversed测试将验证调用模拟对象的Apply方法以生成结果。Apply_Cached_ReturnsReversedCachedValue测试将检查结果是否在不调用模拟对象的Apply方法的情况下返回。
目前的测试并不能证明缓存情况下的结果确实来自缓存。

先生,如果我只创建一个继承我要测试的类的 stubclass,然后修改 if-else 语句以返回类似于“if 被执行”和“else 被执行”的内容,这样可以吗? - Randel Ramirez
1
不行,因为这样你就无法测试你想要测试的实际方法了。 - Andrew Cooper

0

尝试在测试用例中设置缓存字典值,并在调用Apply(string value)方法后检查计数。

` 
       public void Apply_Cached_ReturnsReversedCachedValue()
        {
            Dictionary<string, string> cacheDict = new Dictionary<string, string>() { { "sometext", "txetemos" } };

            string str = "sometext";

            int dictionaryCountBeforeApply = cacheDict.Count();

            //set value to static cache field using reflection, here dictionary count is 1
            Type type = typeof(CachingDecorator);
            FieldInfo cacheFieldInfo = type.GetField("cache", BindingFlags.NonPublic | BindingFlags.Static);
            cacheFieldInfo.SetValue(decorator, cacheDict);

            string result = decorator.Apply(str);

            int dictionaryCountAfterApply = cacheDict.Count();

            Assert.AreEqual(dictionaryCountAfterApply, dictionaryCountBeforeApply);
        }


        public void Apply_NotCached_ReturnsReversed()
        {
            Dictionary<string, string> cacheDict = new Dictionary<string, string>() { };
            string str = "sometext";

            int dictionaryCountBeforeApply = cacheDict.Count();

            //set value to static cache field using reflection, here dictionary count is 0
            Type type = typeof(CachingDecorator);
            FieldInfo cacheFieldInfo = type.GetField("cache", BindingFlags.NonPublic | BindingFlags.Static);
            cacheFieldInfo.SetValue(decorator, cacheDict);

            string result = decorator.Apply(str);

            int dictionaryCountAfterApply = cacheDict.Count();

            Assert.AreNotEqual(dictionaryCountAfterApply, dictionaryCountBeforeApply);
        }`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接