lundi 16 janvier 2012

SpecFlow : StepArgumentTransformation

When writting BDD test features and feature steps, we often need to convert strings to types. Testing strings with a serie of if statement within steps does not maximise reusability and readability. The best would be to get the string recognise as a Type every time we use it in a feature without taking care of the conversion.

SpecFlow provides a StepArgumentTransformation attribute to achieve this :

https://github.com/techtalk/SpecFlow/wiki/Step-Argument-Conversions

Exemple :

 [Then(@"the value of the Shoulder mode is (.*) in the method file")]
public void ThenTheValueOfTheShoulderModeIsDropInTheMethodFile(string shoulderModeString)
{
ShoulderModeType shoulderMode = ShoulderModeType.OFF; ;
if (ShoulderModeType.Drop.ToString() == shoulderModeString) shoulderMode = ShoulderModeType.Drop;
else if (ShoulderModeType.OFF.ToString() == shoulderModeString) shoulderMode = ShoulderModeType.OFF;
else if (ShoulderModeType.Tangential.ToString() == shoulderModeString) shoulderMode = ShoulderModeType.Tangential;
else Assert.Fail("Invalid shoulderModeString: " + shoulderModeString);
...
Assert.AreEqual(expectedShouldMode, shoulderMode)
}


Can be refactored as 


[StepArgumentTransformation]
public ShoulderModeType ShoulderModeTransform(string shoulderModeString)
{
ShoulderModeType shoulderMode = ShoulderModeType.OFF;
if (ShoulderModeType.Drop.ToString() == shoulderModeString) shoulderMode = ShoulderModeType.Drop;
else if (ShoulderModeType.OFF.ToString() == shoulderModeString) shoulderMode = ShoulderModeType.OFF;
else if (ShoulderModeType.Tangential.ToString() == shoulderModeString) shoulderMode = ShoulderModeType.Tangential;
else Debug.Assert.Fail("Invalid shoulderModeString: " + shoulderModeString);
return shoulderMode;
}


[Then(@"the value of the Shoulder mode is (.*) in the method file")]
public void ThenTheValueOfTheShoulderModeIsDropInTheMethodFile(ShoulderModeType shoulderMode)
{
...
Assert.AreEqual(expectedShouldMode, shoulderMode)
}



 



 



 





Share/Bookmark

Aucun commentaire: