Automated or test data is very essential to unit test the
functionality. We can use Fixture to generate automated random data in time of
unit testing.
You can add AutoFixture framework from nugget package
manager .
Let’s see one simple example to generate automated data
using Fixture. Here is my small add functionality which will return addition of
two numbers.
class TestClass
{
public int Add( int a, int b)
{
return a + b;
}
}
And here is code to test the functionality.
[TestClass]
public class UnitTestClass
{
[TestMethod]
public void Add_Test_Function()
{
var fixture = new Fixture();
int x = fixture.CreateAnonymous<int>();
int y = fixture.CreateAnonymous<int>();
var testObject = new Code.TestClass();
Assert.AreEqual(testObject.Add(x,y),x+y);
}
}
In Add_Test_Function , we have created object of Fixture
class and then calling CreateAnonymous<T> function to generate automated
int data because T is specified as integer.
Ok, so we have generated primitive data using fixture, but
how we can generate user defined object ?
In this example we will generate
random user defied object.
Here is our class for which we would like to generate
objects.
class TestClass
{
public int Id { get; set; }
public string Name { get; set; }
public void AddData(IEnumerable<TestClass> param)
{
}
}
Here is test functionality to call AddData function by generating
random object of TestClass class.
[TestClass]
public class UnitTestClass
{
[TestMethod]
public void Add_Test_Function()
{
var fixture = new Fixture();
fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
fixture.Behaviors.Add(new OmitOnRecursionBehavior());
new Code.TestClass().AddData(fixture.CreateMany<Code.TestClass>(new Random().Next(1,20)));
}
}
And we are seeing that it has generated few random objects.
No comments:
Post a Comment