Decorator dynamically gives new behavior to an object that is decorated. This is the responsibility of the decorator. This is what you should check.
, :
public interface IComponent
{
string DoSomething(string value);
}
( TestClass, MSTest)
[TestFixture]
public class CachingComponentTests
{
private CachingComponent _cachingComponent;
private Mock<IComponent> _componentMock;
[SetUp]
public void Setup()
{
_componentMock = new Mock<IComponent>();
_cachingComponent = new CachingComponent(_componentMock.Object);
}
}
CachingComponent, . - ( ):
public class CachingComponent : IComponent
{
private IComponent _component;
public CachingComponent(IComponent component)
{
_component = component;
}
public string DoSomething(string value)
{
throw new NotImplementedException();
}
}
. , :
[Test]
public void ShouldCallComponentWhenCalledFirstTime()
{
_componentMock.Setup(c => c.DoSomething("foo")).Returns("bar");
Assert.That(_cachingComponent.DoSomething("foo"), Is.EqualTo("bar"));
_componentMock.Verify();
}
, . (, , ):
public string DoSomething(string value)
{
return _component.DoSomething(value);
}
. , . . . . :
[Test]
public void ShouldReturnCachedValueWhenCalledMoreThanOnce()
{
_componentMock.Setup(c => c.DoSomething("foo")).Returns("bar");
Assert.That(_cachingComponent.DoSomething("foo"), Is.EqualTo("bar"));
Assert.That(_cachingComponent.DoSomething("foo"), Is.EqualTo("bar"));
_componentMock.Verify(c => c.DoSomething("foo"), Times.Once());
}
:
public class CachingComponent : IComponent
{
private Dictionary<string, string> _cache = new Dictionary<string, string>();
private IComponent _component;
public CachingComponent(IComponent component)
{
_component = component;
}
public string DoSomething(string value)
{
if (!_cache.ContainsKey(value))
_cache.Add(value, _component.DoSomething(value));
return _cache[value];
}
}
.