重构Petapoco生成的项目

时间:2017-06-09 18:01:42

标签: c# unit-testing mocking refactoring petapoco

我使用PetaPoco作为微型ORM创建了一个C#Win Forms应用程序。我想重构生成的类,使它们易于测试和模拟。 当我开始编写单元测试时,我遇到了Mock,因为我没有使用接口,但我不知道如何将接口与当前类集成。

这是课程

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; }
}

然后我扩展这个类

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;
        }
    }

现在当我进行单元测试

    //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));
    }

问题是当我尝试从联盟Stub方法CantTeams时,没有接口模拟抛出和错误。

    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);
    }

单元测试,模拟和模式对我来说是新的,我目前正在尝试学习它们。提前致谢

0 个答案:

没有答案