我想测试 if-else 语句是否被执行,“if”块从字典/缓存中返回项目并返回输出,而“else”块在缓存中添加输入并返回输出
带有方法 Apply 的 IModifyBehavior 接口
我有这个课程:
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));
}
}
先生/女士,您的回答会很有帮助。谢谢++