Are you tired of assert. AreEqal (); and so on? By chance, the following whimsy
Take a look at the following:
AssertThat (something, eq ("Hello "));
AssertThat (something, eq (true ));
AssertThat (something, isA (Color. class ));
AssertThat (something, contains ("World "));
AssertThat (something, same (Food. CHEESE ));
AssertThat (something, NULL );
AssertThat (something, NOT_NULL );
The second parameter is a constraint object, which is the constraint you want to check for something.
This function is cool.
1. Without so many assert methods, it looks comfortable and easier to understand.
2. convenient combination Constraints
AssertThat (something, not (eq ("Hello ")));
AssertThat (something, not (contains ("Cheese ")));
3. Custom constraints.
AssertThat (something, between (10, 20 ));
Public Constraint between (final int min, final int max ){
Return new Constraint (){
Public boolean eval (Object object ){
If (! Object instanceof Integer ){
Return false;
}
Int value = (Integer) object). intValue ();
Return value> min & value <max;
}
}
}
In fact, this is also the idea of separation of responsibility. Why can't we think of it? Of course, in Nunit, this constraint can be implemented through Delegate. I have simulated the implementation under NUnit. Is there any better implementation? Using System;
Namespace xnUnit
{
Class Constraint
{
Public delegate bool EvalDelegate (object obj );
Public EvalDelegate EvalHandle;
Public bool Eval (object obj)
{
Return EvalHandle (obj );
}
}
Class Assert
{
Public static void AssertThat (object obj, Constraint con)
{
If (con. Eval (obj ))
{
Console. WriteLine ("Pass ");
}
Else
{
Console. WriteLine ("Failed! ");
}
}
}
}
Using System;
Namespace xnUnit
{
Class Program
{
Public static Constraint Between (int min, int max)
{
Constraint con = new Constraint ();
Con. EvalHandle = delegate (object obj)
{
Int value = Convert. ToInt32 (obj );
Return value> min & value <max;
};
Return con;
}
Static void Main (string [] args)
{
Assert. AssertThat (3, Between (2, 4 ));
}
}
}