Skip to content

Instantly share code, notes, and snippets.

@rabelloo
Last active July 17, 2020 11:41
Show Gist options
  • Save rabelloo/d1924869a92b5a40802572880e51b234 to your computer and use it in GitHub Desktop.
Save rabelloo/d1924869a92b5a40802572880e51b234 to your computer and use it in GitHub Desktop.
C# Expect inspired by Jasmine
public class Expect
{
private object expectation;
protected bool not;
public Expect(object expectation)
{
this.expectation = expectation;
}
public Expect Not { get { not = !not; return this; } }
public void ToBe (object actual) => Verify(Compare, actual, "be");
public void ToEqual(object actual) => Verify(Similar, actual, "equal");
protected bool Compare(object actual)
=> System.Convert.GetTypeCode(expectation) == System.TypeCode.Object
? ReferenceEquals(expectation, actual) != not
: Equals(expectation, actual) != not;
protected bool Similar(object actual)
=> System.Convert.GetTypeCode(expectation) == System.TypeCode.Object
? Equals(Serialize(expectation), Serialize(actual)) != not
: Equals(expectation, actual) != not;
protected string Serialize(object obj) => Newtonsoft.Json.JsonConvert.SerializeObject(obj);
protected void Verify(System.Func<object, bool> verifier, object actual, string comparation)
{
if (!verifier(actual))
{
Throw(actual, comparation);
}
}
protected void Throw(object actual, string comparation)
=> throw new System.Exception($"Expected <{expectation}> {(not ? "not " : "")} to {comparation} <{actual}>");
}
[TestClass]
public class ExpectTest
{
[TestMethod]
public void Bool()
{
new Expect(true).ToBe(true);
new Expect(true).Not.ToBe(false);
}
[TestMethod]
public void String()
{
new Expect("a").ToBe("a");
new Expect("a").Not.ToBe("b");
new Expect("a").Not.ToBe("A");
}
[TestMethod]
public void Int()
{
new Expect(1).ToBe(1);
new Expect(1 > 2).ToBe(false);
new Expect(1 >= 2).ToBe(false);
new Expect(1 < 2).ToBe(true);
new Expect(1 <= 2).ToBe(true);
}
[TestMethod]
public void Object()
{
var obj = new { a = 1 };
new Expect(obj).ToBe(obj);
new Expect(obj).Not.ToBe(new { a = 1 });
new Expect(obj).ToEqual(new { a = 1 });
new Expect(obj).Not.ToEqual(new { a = 2 });
}
[TestMethod]
public void Array()
{
var array = new int[] { 1, 2, 3, 4 };
new Expect(array).ToBe(array);
new Expect(array).Not.ToBe(new int[] { 1, 2, 3, 4 });
new Expect(array).ToEqual(new int[] { 1, 2, 3, 4 });
new Expect(array).Not.ToEqual(new int[] { 1, 2, 3 });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment