Skip to content

Instantly share code, notes, and snippets.

@slmcmahon
Created November 26, 2010 16:47
Show Gist options
  • Save slmcmahon/716944 to your computer and use it in GitHub Desktop.
Save slmcmahon/716944 to your computer and use it in GitHub Desktop.
Demonstrates a way to use TryParse to convert numbers
using System;
using NUnit.Framework;
namespace NumberConversions
{
[TestFixture]
public class ConversionTests
{
private const string VALID_NUMBER = "12345";
private const string INVALID_NUMBER = "BR549";
private const int EXPECTED_NUMBER = 12345;
[Test]
public void TestConvertValidNumber()
{
var response = Convert.ToInt32(VALID_NUMBER);
Assert.That(response, Is.EqualTo(EXPECTED_NUMBER));
}
[Test]
[ExpectedException(typeof(FormatException))]
public void TestConvertInvalidNumber()
{
Convert.ToInt32(INVALID_NUMBER);
}
[Test]
public void TestTryParseValidNumber()
{
int num;
var result = (Int32.TryParse(VALID_NUMBER, out num)) ? num : -1;
Assert.That(result, Is.EqualTo(EXPECTED_NUMBER));
}
[Test]
public void TestTryParseInvalidNumber()
{
int num;
var result = (Int32.TryParse(INVALID_NUMBER, out num)) ? num : -1;
Assert.That(result, Is.EqualTo(-1));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment