我想测试if-else语句是否被执行,“if”块返回字典/缓存中的项目并返回输出,而“else”块将输入添加到缓存中并返回输出如何在C#中使用stubclass单元测试if-else语句?
IModifyBehavior的一个方法的接口应用
我能够正确地执行它使用最小起订量,但现在我想尝试只是使用stubclass(无框架)的单元测试,我也想实现它,而不使用假货。
我有这个类:
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));
}
}
先生/女士您的回答会有很大的帮助。谢谢++
我只是想以不同的方式尝试它,因为我正在学习单元测试,我对它很陌生,所以我想看看我将如何实现它。 – 2013-03-14 01:12:15
这里有一些有用的测试链接可能会帮助你,如果你稍后再回来查看,我目前正在TDD http:// bobthejanitor上工作。org/2012/06/running-your-test-while-you-write-them.html,http://bobthejanitor.org/2012/06/behavioral-testing-with-nunit.html,http://bobthejanitor。组织/ 2012/06 /测试换处决sequence.html – 2013-03-14 13:54:27