Skip to content

Instantly share code, notes, and snippets.

@ZachBray
Created April 7, 2014 23:33
Show Gist options
  • Save ZachBray/10073529 to your computer and use it in GitHub Desktop.
Save ZachBray/10073529 to your computer and use it in GitHub Desktop.
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cache.Tests
{
[TestFixture]
public class CacheTests
{
private ObservableLatestOnNextCache<string, int> _sut;
[SetUp]
public void SetUp()
{
_sut = new ObservableLatestOnNextCache<string, int>();
}
[Test]
public void Should_only_create_observable_once()
{
// Arrange
bool wasXsCreated = false;
bool wasYsCreated = false;
// Act
var xs = _sut.FindOrCreate("key", () => Observable.Create<int>(o =>
{
wasXsCreated = true;
return Disposable.Empty;
}));
var ys = _sut.FindOrCreate("key", () => Observable.Create<int>(o =>
{
wasYsCreated = true;
return Disposable.Empty;
}));
xs.Subscribe();
ys.Subscribe();
// Assert
var createdXsNotYs = wasXsCreated && !wasYsCreated;
Assert.That(createdXsNotYs);
}
[Test]
public void Should_replay_latest_value_to_new_subscriber()
{
// Arrange
IObserver<int> observer = null;
var cachedValuesForKey = _sut.FindOrCreate("key", () => Observable.Create<int>(o => {
observer = o;
return Disposable.Empty;
}));
cachedValuesForKey.Subscribe();
observer.OnNext(3);
observer.OnNext(7);
observer.OnNext(31);
// Act
int observedValue = default(int);
cachedValuesForKey.Subscribe(x => observedValue = x);
// Assert
Assert.AreEqual(31, observedValue);
}
[Test]
public void Should_subscribe_again_on_error()
{
// Arrange
int connectionCount = 0;
IObserver<int> observer = null;
var cachedValuesForKey = _sut.FindOrCreate("key", () => Observable.Create<int>(o =>
{
connectionCount++;
observer = o;
return Disposable.Empty;
}));
// Act
Exception error = null;
cachedValuesForKey.Subscribe(x => { }, ex => error = ex);
observer.OnError(new Exception());
Assume.That(error != null);
Exception subsequentError = null;
int observedValue = default(int);
cachedValuesForKey.Subscribe(x => observedValue = x, ex => subsequentError = ex);
observer.OnNext(31);
Assume.That(subsequentError == null);
Assume.That(observedValue == 31);
// Assert
Assert.AreEqual(2, connectionCount);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment