首先模拟代码实体框架实体

时间:2017-09-15 02:02:04

标签: c# entity-framework unit-testing entity-framework-core

假设我有一个这样的课程

   public class FooEntity
   {
        private BarEntity Bar;

        public void DoSomething()
        {
            var result = Bar.DoSomethingElse();

            if (result)
                DoThis();

            else
                DoThat();

        }

        private void DoThis() { }

        private void DoThat() { }
   }

我正在尝试测试FooEntity。从单元测试的角度来看,我想模拟BarEntity并提供测试结果,因为我没有测试BarEntity。

我见过的每个模拟框架似乎都需要模拟接口。最后,我检查了不支持在Entity Framework中使用接口作为导航属性。我知道我可以添加一个未映射的属性到我的接口类型的实体并使用它。为了满足一些测试,这样做似乎有点麻烦。

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

using Moq;

public class FooEntity
{
    //if Bar is a table, you should write like this:
    public virtual BarEntity Bar {get;set;}
    public int BarId {get;set;}

    public void DoSomething()
    {
        var result = Bar.DoSomethingElse();

        if (result)
            DoThis();
        else
            DoThat();
    }

    private void DoThis() { }
    private void DoThat() { }
}

var mock = new Mock<BarEntity>();
//DoSomethingElse method should be virtual and BarEntity should not be sealed
mock.Setup(x => x.DoSomethingElse()).Returns(true);//or false
var target2test = new FooEntity { Bar = mock.Object };
//action:
target2test.DoSomething();//will result to DoThis calling