I wrote a class that is an enumerable wrapper that caches the results of a base enumerable, only getting the next element if we enumerate and get to the end of the cached results. It can be multithreaded (getting the next item in another thread) or single-threaded (getting the next item in the current thread).
I read on unit-testing and would like my head around the relevant tests. I am using nunit . My main problem is that I have already written my class and am using it. It works for what I use for it (currently one). So, I write my tests, just trying to think about things that may go wrong, which, given that I tested informally, I probably unconsciously write tests that, as I know, have already been tested. How can I get a recording balance between too many / fine tests and too few tests?
- Should I test only public methods / constructors or should I test each method?
- Should I test the
CachedStreamingEnumerable.CachedStreamingEnumerator class separately? - Currently, I am only testing when the class is set to single-threaded. How can I test it with multithreading, given that it may take me a while before the item is fetched and added to the cache?
- What tests are I missing to provide good coverage? I don’t need it anymore?
The code for the class and the testing class are below.
CachedStreamingEnumerable
CachedStreamingEnumerableTests
[TestFixture] public class CachedStreamingEnumerableTests { public bool EnumerationsAreSame<T>(IEnumerable<T> first, IEnumerable<T> second) { if (first.Count() != second.Count()) return false; return !first.Zip(second, (f, s) => !s.Equals(f)).Any(diff => diff); } [Test] public void InstanciatingWithNullParameterThrowsException() { Assert.Throws<ArgumentNullException>(() => new CachedStreamingEnumerable<int>(null, false)); } [Test] public void SameSequenceAsUnderlyingEnumerationOnceCached() { var SourceEnumerable = Enumerable.Range(0, 10); var CachedEnumerable = new CachedStreamingEnumerable<int>(SourceEnumerable, false); // Enumerate the cached enumerable completely once for each item, so we ensure we cache all items foreach (var x in SourceEnumerable) { foreach (var i in CachedEnumerable) { } } Assert.IsTrue(EnumerationsAreSame(Enumerable.Range(0, 10), CachedEnumerable)); } [Test] public void CanNestEnumerations() { var SourceEnumerable = Enumerable.Range(0, 10).Select(i => (decimal)i); var CachedEnumerable = new CachedStreamingEnumerable<decimal>(SourceEnumerable, false); Assert.DoesNotThrow(() => { foreach (var d in CachedEnumerable) { foreach (var d2 in CachedEnumerable) { } } }); } }
source share