I wrote this class...
namespace PrivateMethodTesting.Models
{
public class SummationScienceExperiment
{
public int DependentVariable { get; private set; }
public int IndependentVariable { get; private set; }
public double? DivisionCalculation { get; private set; }
public SummationScienceExperiment(int ofStone, int ofClay)
{
DependentVariable = ofStone;
IndependentVariable = ofClay;
DivisionCalculation = craftDecimal(ofStone, ofClay);
}
public void Update(int ofClay)
{
IndependentVariable = ofClay;
DivisionCalculation = craftDecimal(DependentVariable, ofClay);
}
private double? craftDecimal(int ofStone, int ofClay)
{
if (ofClay == 0) return null;
return (double)ofStone/(double)ofClay;
}
}
}
...and then I wrote the following four tests around it. The last test uses reflection to test the private method.
using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PrivateMethodTesting.Models;
namespace PrivateMethodTesting.Tests
{
[TestClass]
public class SummationScienceExperimentTests
{
[TestMethod]
public void constructor_should_craft_a_decimal()
{
SummationScienceExperiment foo = new SummationScienceExperiment(5,2);
Assert.AreEqual(5, foo.DependentVariable);
Assert.AreEqual(2, foo.IndependentVariable);
Assert.AreEqual(2.5, foo.DivisionCalculation);
}
[TestMethod]
public void update_should_craft_a_decimal()
{
SummationScienceExperiment foo = new SummationScienceExperiment(5, 2);
foo.Update(4);
Assert.AreEqual(5, foo.DependentVariable);
Assert.AreEqual(4, foo.IndependentVariable);
Assert.AreEqual(1.25, foo.DivisionCalculation);
}
[TestMethod]
public void may_divide_zero()
{
SummationScienceExperiment foo = new SummationScienceExperiment(0, 2);
Assert.AreEqual(0, foo.DependentVariable);
Assert.AreEqual(2, foo.IndependentVariable);
Assert.AreEqual(0, foo.DivisionCalculation);
}
[TestMethod]
public void may_not_divide_by_zero()
{
Type type = typeof(SummationScienceExperiment);
var infos = type.GetMethods(BindingFlags.NonPublic|BindingFlags.Instance);
MethodInfo info = infos[3];
SummationScienceExperiment foo = new SummationScienceExperiment(5, 2);
Assert.AreEqual(info.Invoke(foo, new object[] { foo.DependentVariable, 0 }),null);
}
}
}
No comments:
Post a Comment