ModelValidation.Test
v.1.0.0
إطار صغير للتحقق من صحة النماذج بشكل صحيح.
يمكن أن أكون مفيدًا أيضًا لنهج TDD (التطوير الذي يحركه الاختبار) لتطوير النموذج.
إنه يعمل فعليًا مع أي إطار اختبار!
تثبيته من nuget: https://www.nuget.org/packages/modelvalidation.test
مثال على الاستعلام:
[ YoungSkywalker ] // Surname == Skywalker && Age < 25
public class Rebel
{
[ Required ]
[ MaxLength ( 10 ) ]
public string Name { get ; set ; }
[ Required ]
public string Surname { get ; set ; }
[ Range ( 10 , 900 ) ]
public int Age { get ; set ; }
[ RebelWeapon ] // Color == "Green"
public Weapon Weapon { get ; set ; }
}
public class Weapon
{
public string Color { get ; set ; }
}
[ Fact ]
public void Test_Luke ( )
{
ModelValidator . Test (
( ) => new Rebel
{
Name = "Luke" ,
Surname = "Skywalker" ,
Age = 18 ,
Weapon = new Weapon
{
Color = "Green"
}
} ,
modelSetup =>
{
modelSetup . CheckClass ( os => os . IsInvalidWith ( r => r . Surname , "Organa" ) ) ;
modelSetup . CheckClass ( os => os . IsInvalidWith ( r => r . Age , 42 ) ) ;
modelSetup . CheckProperty ( r => r . Name , ps => ps . IsInvalidWith ( null ) . IsInvalidWith ( "Lukelongname" ) ) ;
modelSetup . CheckProperty ( r => r . Surname , ps => ps . IsInvalidWith ( null ) ) ;
modelSetup . CheckProperty ( r => r . Age , ps => ps . IsInvalidWith ( 901 ) . IsInvalidWith ( 9 ) ) ;
modelSetup . CheckProperty ( r => r . Weapon , ps => ps . IsInvalidWithTransform ( w =>
{
w . Color = "Red" ;
return w ;
} ) ) ;
} ) ;
}
// Test that validation attributes return the correct message
[ Fact ]
public void Test_Stormtrooper ( )
{
ModelValidator . Test (
( ) => new Stormtrooper
{
IsCloned = true ,
Leader = "Palpatine"
} ,
modelSetup =>
{
modelSetup . CheckObject ( os => os . IsInvalidWith ( r => r . IsCloned , false ) , "Trooper must be a clone." ) ;
modelSetup . CheckProperty ( r => r . Leader , ps => ps . IsInvalidWith ( null , "Sith leader is required." ) ) ;
} ) ;
} هناك بعض طرق التمديد المدمجة للمساعدة في كتابة اختبارات الخصائص بشكل أسرع:
ps.IsRequired()ps.HasMaxLenght(int)ps.HasMinLenght(int)ps.HasMinValue(int)ps.HasMaxValue(int)ps.InRange(int, int)ps.HasMinValue(double)ps.HasMaxValue(double)ps.InRange(double, double) // Example
[ Fact ]
ModelValidator . Test (
( ) => new Stormtrooper
{
IsCloned = true ,
Leader = "Palpatine"
} ,
modelSetup =>
{
modelSetup . CheckProperty ( r => r . Leader , ps => ps . IsRequired ( ) ) ;
} ) ; تقبل طريقة Test كائن الخيار كمعلمة ثالثة.