I'm creating a C# Win Forms app using PetaPoco as micro ORM. I want to refactor the generated classes to make them easily testable and mockable. When I started to write the Unit Test I get stuck with Mock because I do not use interfaces, but I dont know how to integrate the interfaces with the current classes.
This are the classes
public partial class League : FutbolDB.Record<League>
{
public int? id { get; set; }
public string Name { get; set; }
public int? CantTeams { get; set; }
}
public partial class Team : FutbolDB.Record<Team>
{
public int? id { get; set; }
public string Name { get; set; }
private int? LeagueId { get; set; }
}
Then I extend this classes
public partial class Team : FutbolDB.Record<Team>
{
private League _league;
public Team() {}
public Team(string name, League league)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("The name cannot be empty or null");
if (league == null)
throw new ArgumentException("The League cannot be null");
Name = name;
League = league;
}
[Ignore]
public League League
{
get { return _league ?? League.GetById(LeagueId); }
set {
_league = value;
LeagueId = _league?.id;
}
}
Now when I Unit Test
//this runs fine
[TestMethod()]
public void EqualsTest()
{
Mock<League> mockLeague = new Mock<League>();
var t1 = new Team("team",mockLeague.Object);
var t2 = new Team("Team", mockLeague.Object);
t1.id = 1;
t2.id = 1;
Assert.IsTrue(t1.Equals(t1));
Assert.IsFalse(t1.Equals(null));
Assert.IsTrue(t1.Equals(t2));
}
The problem is when I try to Stub the method CantTeams from League, that without interfaces Mock throws and error.
public TeamTests()
{
List<Team> teams = new List<Team>();
teams.Add(new Team("barca", mockLeague.Object));
teams.Add(new Team("atletico", mockLeague.Object));
teams.Add(new Team("madrid", mockLeague.Object));
// Error stubbing this method from a concrete class
mockLeague.Setup(x => x.CantTeams).Returns(teams.Count);
}
Unit testing, Mock and Patterns are new to me and I'm currently trying to learn them. Thanks in advance