Tôi khá mới để thử nghiệm đơn vị (tôi thực sự đang nghiên cứu nó khi chúng tôi nói)C# Làm thế nào để đơn vị đúng kiểm tra một lớp học mà theo một mẫu trang trí?
Mục tiêu của tôi tất nhiên là có thể kiểm tra phương thức bên trong lớp bên dưới. Lớp học chỉ đơn giản là kiểm tra nếu đầu vào đã có trong bộ nhớ cache, nếu đầu vào không có trong bộ đệm, nó sẽ trả về dạng đảo ngược của đầu vào (mặc dù việc thực hiện không có ở đây, nhưng giả sử nó có, vì mục đích chỉ là để kiểm tra).
Về cơ bản, mục tiêu là đảm bảo nếu người khác được kiểm tra.
Đây là lớp học của tôi:
namespace YouSource.Decorator
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Caching Decorator
/// </summary>
public class CachingDecorator : IModifyBehavior
{
private IModifyBehavior behavior;
private static Dictionary<string, string> cache =
new Dictionary<string, string>();
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";
cache.Add(value, result);
}
return result;
}
}
}
Đây là mã hiện tại của thử nghiệm của tôi:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace YouSource.Decorator.Tests
{
[TestClass]
public class CachingDecoratorTest
{
private IModifyBehavior behavior;
[TestInitialize]
public void Setup()
{
this.behavior = new StubModifyBehavior(new CachingDecorator());
}
[TestCleanup]
public void Teardown()
{
this.behavior = null;
}
[TestMethod]
public void Apply_Cached_ReturnsReversedCachedValue()
{
string input = "randel";
string reversed = "lednar";
Assert.AreEqual(reversed, this.behavior.Apply(input));
}
[TestMethod]
public void Apply_NotCached_ReturnsReversed()
{
string input = "not cached";
string reversed = "reversed";
Assert.AreEqual(reversed, this.behavior.Apply(input));
}
public class StubModifyBehavior : IModifyBehavior
{
private IModifyBehavior behavior;
public StubModifyBehavior(IModifyBehavior behavior)
{
this.behavior = behavior;
}
public string Apply(string value)
{
//return this.behavior.Apply(value);
}
}
}
}