Skip to content

Instantly share code, notes, and snippets.

@ZhenDeng
Created March 6, 2018 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZhenDeng/78b101cb30aa465a135bf181dcc65646 to your computer and use it in GitHub Desktop.
Save ZhenDeng/78b101cb30aa465a135bf181dcc65646 to your computer and use it in GitHub Desktop.
Model:
public class OrganisationVM
{
public int Id { get; set; }
[Required]
[MinLength(5, ErrorMessage = "Must be at least 5 characters long")]
public string Name { get; set; }
[Required]
[Range(1, 100000, ErrorMessage = "Must be greater than 1 and less than 1000000")]
public int Employees { get; set; }
}
XUnitTest:
public class OrganisationVMTest
{
[Fact]
public void OrganisationVMValid()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Name = "Julian",
Employees = 1000
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.True(valid);
}
[Fact]
public void OrganisationVM_name_required()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Employees = 1000
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.False(valid);
var failure = Assert.Single(
result,
x => x.ErrorMessage == "The Name field is required.");
Assert.Single(failure.MemberNames, x => x == "Name");
}
[Fact]
public void OrganisationVM_Name_Short()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Name = "July",
Employees = 1000
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.False(valid);
var failure = Assert.Single(
result,
x => x.ErrorMessage == "Must be at least 5 characters long");
Assert.Single(failure.MemberNames, x => x == "Name");
}
[Fact]
public void OrganisationVM_Employee_Range()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Name = "Julian",
Employees = 0
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.False(valid);
var failure = Assert.Single(
result,
x => x.ErrorMessage == "Must be greater than 1 and less than 1000000");
Assert.Single(failure.MemberNames, x => x == "Employees");
}
[Fact]
public void OrganisationVM_Employee_Required()
{
// Arrange
var model = new OrganisationVM
{
Id = 1,
Name = "Julian"
};
var context = new ValidationContext(model, null, null);
var result = new List<ValidationResult>();
// Act
var valid = Validator.TryValidateObject(model, context, result, true);
Assert.False(valid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment