Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save k0stya/5019208 to your computer and use it in GitHub Desktop.
Save k0stya/5019208 to your computer and use it in GitHub Desktop.
If the system under test (SUT) was not designed specifically to be testable, we may find that the test cannot get access to state that it must initialize or verify at some point in the test.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace TestDoubles.Examples.TestSpecificSubclass.ProtectedMember
{
[TestClass]
public class Player_Test
{
[TestMethod]
public void Should_be_able_to_roll_die_wtih_max_face_value()
{
// Arrange
var mock = new Mock<IDie>();
mock.Setup(m => m.Roll()).Returns(6);
var player = new TestSpecificPlayer(mock.Object);
// Act
player.RollDie();
// Assert
Assert.AreEqual(6, player.PublicUnitsToMove);
}
}
public class Player
{
private readonly IDie _die;
protected Player(IDie die)
{
_die = die;
}
protected int UnitsToMove { get; set; }
public void RollDie()
{
UnitsToMove = _die.Roll();
// Some extra logic here
}
}
class TestSpecificPlayer : Player
{
public TestSpecificPlayer(IDie die)
: base(die)
{
}
public int PublicUnitsToMove
{
get { return UnitsToMove; }
}
}
public interface IDie
{
int Roll();
}
public class Die : IDie
{
public int Roll()
{
// Random number :)
return 5;
}
}
}
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace TestDoubles.Examples.TestSpecificSubclass
{
[TestClass]
public class Player_Test
{
[TestMethod]
public void Should_be_able_to_roll_die_wtih_max_face_value()
{
// Arrange
var mock = new Mock<IDie>();
var player = new TestSpecificPlayer(mock.Object);
// Act
player.RollDie();
player.RollDie();
// Assert
mock.Verify(m => m.Roll(), Times.Once(), "only one roll is allowed at once");
}
}
public abstract class Player
{
private readonly IDie _die;
private bool _isMyTurn;
protected Player(IDie die)
{
_die = die;
}
public int UnitsToMove { get; set; }
public void RollDie()
{
if (_isMyTurn)
UnitsToMove = _die.Roll();
_isMyTurn = false;
// Some extra logic here
}
}
class TestSpecificPlayer : Player
{
public TestSpecificPlayer(IDie die) : base(die)
{
}
}
public interface IDie
{
int Roll();
}
public class Die : IDie
{
public int Roll()
{
// Random number :)
return 5;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment