2010年5月22日土曜日

HskellのMaybeクラスをC#で作ってみた。その3


HaskellのMaybeクラスをC#で作ってみた。その2
で作成した
Maybeクラスの単体テストもNUnitを使って書いているので、
それも一緒に公開しておきます。



[TestFixture]
public class MaybeTest
{
[Test]
public void MaybeNothingTest()
{
Maybe<int> nothing = Maybe<int>.Nothing;
Assert.IsFalse(nothing.HasValue);
Assert.Throws<InvalidOperationException>(delegate { int i = nothing.Value; });
}

[Test]
public void MaybeFromTset()
{
DoMaybeFromTest((int)1);
DoMaybeFromTest(DateTime.Now);
DoMaybeFromTest(new InvalidOperationException());
DoMaybeFromTest(new Action<int>(DoMaybeFromTest));
}
[Test]
public void MaybeFromArgumentNullTset()
{
Assert.Throws<ArgumentNullException>(delegate { Maybe<InvalidOperationException>.Just(null); });
}

private static void DoMaybeFromTest<T>(T value)
{
Maybe<T> maybe = Maybe<T>.Just(value);
Assert.IsTrue(maybe.HasValue);
Assert.AreEqual(value, maybe.Value);
}
[Test]
public void GetValueTest()
{
Maybe<int> nothing = Maybe<int>.Nothing;
Assert.AreEqual(1, nothing.GetValue(1));

Maybe<int> maybe = Maybe<int>.Just(20);
Assert.AreEqual(20, maybe.GetValue(1));
}
[Test]
public void EqualsTest()
{
Assert.IsTrue(Maybe<int>.Nothing.Equals(Maybe<int>.Nothing));
Assert.IsTrue(Maybe<int>.Just(1).Equals(Maybe<int>.Just(1)));
Assert.IsTrue(Maybe<DateTime>.Just(new DateTime(2000, 10, 10, 10, 10, 10)).Equals(Maybe<DateTime>.Just(new DateTime(2000, 10, 10, 10, 10, 10))));

Assert.IsFalse(Maybe<int>.Nothing.Equals(null));
Assert.IsFalse(Maybe<int>.Nothing.Equals(Maybe<int>.Just(1)));
Assert.IsFalse(Maybe<int>.Just(19).Equals(Maybe<int>.Just(1)));
}

[Test]
public void OperatorEqualsTest()
{
Assert.IsTrue(Maybe<int>.Nothing == Maybe<int>.Nothing);
Assert.IsTrue(Maybe<int>.Just(1) == Maybe<int>.Just(1));
Assert.IsTrue(Maybe<DateTime>.Just(new DateTime(2000, 10, 10, 10, 10, 10)) == Maybe<DateTime>.Just(new DateTime(2000, 10, 10, 10, 10, 10)));

Assert.IsFalse(Maybe<int>.Nothing == null);
Assert.IsFalse(null == Maybe<int>.Nothing);
Assert.IsFalse(Maybe<int>.Nothing == Maybe<int>.Just(1));
Assert.IsFalse(Maybe<int>.Just(19) == Maybe<int>.Just(1));
}
[Test]
public void OperatorNotEqualsTest()
{
Assert.IsFalse(Maybe<int>.Nothing != Maybe<int>.Nothing);
Assert.IsFalse(Maybe<int>.Just(1) != Maybe<int>.Just(1));
Assert.IsFalse(Maybe<DateTime>.Just(new DateTime(2000, 10, 10, 10, 10, 10)) != Maybe<DateTime>.Just(new DateTime(2000, 10, 10, 10, 10, 10)));

Assert.IsTrue(Maybe<int>.Nothing != null);
Assert.IsTrue(null != Maybe<int>.Nothing);
Assert.IsTrue(Maybe<int>.Nothing != Maybe<int>.Just(1));
Assert.IsTrue(Maybe<int>.Just(19) != Maybe<int>.Just(1));
}

[Test]
public void CastTest()
{
Maybe<Encoding> maybe = Maybe<Encoding>.Just(Encoding.UTF8);
Assert.AreEqual(Encoding.UTF8, (Encoding)maybe);
}
}

0 件のコメント:

ラベル