Instantly share code, notes, and snippets.

@Lumirris /UserName.cs Secret
Last active Aug 29, 2015

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UserNameValidation
{
public class UserName
{
private readonly string value;
public UserName(string value)
{
if (value == null)
throw new ArgumentNullException("value");
if (!UserName.IsValid(value))
throw new ArgumentException("Invalid value.", "value");
this.value = value;
}
public static bool IsValid(string candidate)
{
if (string.IsNullOrEmpty(candidate))
return false;
return candidate.Trim().ToUpper() == candidate;
}
public static bool TryParse(string candidate, out UserName userName)
{
userName = null;
if (string.IsNullOrWhiteSpace(candidate))
return false;
userName = new UserName(candidate.Trim().ToUpper());
return true;
}
public static implicit operator string(UserName userName)
{
return userName.value;
}
public override string ToString()
{
return this.value.ToString();
}
public override bool Equals(object obj)
{
var other = obj as UserName;
if (other == null)
return base.Equals(obj);
return object.Equals(this.value, other.value);
}
public override int GetHashCode()
{
return this.value.GetHashCode();
}
}
}
using System;
using Xunit;
using Xunit.Extensions;
namespace UserNameValidation
{
public class UserNameTests
{
[Theory]
[Trait("Instantiation", "Constructor")]
[InlineData("jeff")]
[InlineData("JEFF")]
public void PassingValidValuesToConstructorDoesNotThrowException(string expected)
{
Assert.ThrowsDelegate act = () => new UserName(expected);
Assert.DoesNotThrow(act);
}
[Theory]
[Trait("Instantiation", "Constructor")]
[InlineData("", typeof(ArgumentException))]
[InlineData(" ", typeof(ArgumentException))]
[InlineData(null, typeof(ArgumentNullException))]
public void PassingInvalidValuesToConstructorThrowsException(string expected, Type exceptionType)
{
Assert.ThrowsDelegate act = () => new UserName(expected);
Assert.Throws(exceptionType, act);
}
[Theory]
[Trait("Instantiation", "TryParse")]
[InlineData("jeff", true)]
[InlineData("JEFF", true)]
[InlineData("", false)]
[InlineData(" ", false)]
[InlineData(null, false)]
public void PassingValuesToTryParseReturnsExpectedValue(string candidate, bool expected)
{
// arrange
UserName userName;
// act
var actual = UserName.TryParse(candidate, out userName);
// assert
Assert.Equal(expected, actual);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment