Skip to content

Sample Attribute

Averrunci edited this page Apr 14, 2017 · 1 revision

This attribute is used to provide sample data or its source.

The available properties are as follows.

Property Description
Data Specifies sample data using parameters of a constructor. If the Source property is specified, this is ignored.
Description Specifies a description of sample data. If the Source property is specified, this is ignored.
Source Specifies a source type of sample data. This type must implement ISampleDataSource and have a parameterless constructor.

For example:

[Specification("LoginAuthentication specification")]
class LoginAuthenticationSpec
{
    [Example("Login authentication is failed")]
    [Sample(null, "pass", Description = "When a user id is null")]
    [Sample("", "pass", Description = "When a user id is empty")]
    [Sample("user", null, Description = "When a password is null")]
    [Sample("user", "", Description = "When a password is empty")]
    [Sample("user", "pass", Description = "When a user id or password is invalid")]
    void Ex01(string userId, string password)
    {
        ...
    }
}

When a source is specified, its source type must implement ISampleDataSource. ISampleDataSource defines the GetData method that returns IEnumerable and does not have a parameter. The object that is contained by the IEnumerable has properties that indicate sample data. The property name is equal to a parameter name of the specified fixture method. Its case is ignored. If you want to specify a description of the sample fixture, define a property whose name is 'Description'.

For example:

[Specification("LoginAuthentication specification")]
class LoginAuthenticationSpec
{
    [Example("Login authentication is failed")]
    [Sample(Source = typeof(FailedLoginDataSource))]
    void Ex01(string userId, string password)
    {
        ...
    }
}

class FailedLoginDataSource : ISampleDataSource
{
    IEnumerable ISampleDataSource.GetData()
    {
        yield return new { Description = "When a user id is null", UserId = null, Password = "pass" };
        yield return new { Description = "When a user id is empty", UserId = string.Empty, Password = "pass" };
        yield return new { Description = "When a password is null", UserId = "user", Password = null };
        yield return new { Description = "When a password is empty", UserId = "user", Password = string.Empty };
        yield return new { Description = "When a user id or password is invalid", UserId = "user", Password = "pass" };
    }
}
Clone this wiki locally