Note that there are some explanatory texts on larger screens.

plurals
  1. POC# How to properly unit test a class that follows a decorator pattern?
    primarykey
    data
    text
    <p>I'm fairly new to unit testing(I'm actually studying it as we speak)</p> <p>My goal is of course to be able to test the method inside the class below.</p> <p>The class simply checks if the input is already in the cache, if the input is not in the cache, it will return the reversed form of the input(though the implementation is not here, but assuming it does, since the purpose is just to test).</p> <p>Basically the goal is to make sure the if-else is tested.</p> <p>Here is my class:</p> <pre><code>namespace YouSource.Decorator { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// &lt;summary&gt; /// Caching Decorator /// &lt;/summary&gt; public class CachingDecorator : IModifyBehavior { private IModifyBehavior behavior; private static Dictionary&lt;string, string&gt; cache = new Dictionary&lt;string, string&gt;(); 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; } } } </code></pre> <p>Here is the current code of my test:</p> <pre><code>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); } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload