1 Replies - 602 Views - Last Post: 06 October 2017 - 11:20 AM

#1 fearfulsc2  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 169
  • Joined: 25-May 16

Unit Test Entity Framework with .Any

Posted 06 October 2017 - 05:37 AM

Hello everyone, I am trying to write a unit test for entity framework and I can't seem to get this one test to pass with the right mocked information.

My class goes something like

var someObject = new List<SomeObject>();

try
{
  someObject = this.db.SomeObjects.Where(d => d.JunctionTable.Any(f => f.Id == passedInId)).ToList();
}



So I am trying to unit test that, but I can't seem to get it to return the mocked object that I created.

My unit test looks something like

this.mockDb = new Mock<DbEntities>();

var data = new List<SomeObject2>
{
  new SomeObject2() { Id1 = 1, Id2 = 1},
  new SomeObject2() { Id1 = 2, Id2 = 2}
}.AsQueryable();

var data2 = new List<SomeObject1>
{
  this.mockedObject // I created this mocked object outside of this
}.AsQueryable();

var objectInfo1 = new Mock<Dbset<SomeObject2>>();
objectInfo1.As<IQueryable<SomeObject2>>().Setup(m => m.Provider).Returns(data.Provider);
objectInfo1.As<IQueryable<SomeObject2>>().Setup(m => m.Expression).Returns(data.Expression);
objectInfo1.As<IQueryable<SomeObject2>>().Setup(m => m.ElementType).Returns(data.ElementType);
objectInfo1.As<IQueryable<SomeObject2>>().Setup(m => m.GetEnumerator).Returns(data.GetEnumerator);

var objectInfo2 = new Mock<Dbset<SomeObject1>>();
objectInfo2.As<IQueryable<SomeObject1>>().Setup(m => m.Provider).Returns(data2.Provider);
objectInfo2.As<IQueryable<SomeObject1>>().Setup(m => m.Expression).Returns(data2.Expression);
objectInfo2.As<IQueryable<SomeObject1>>().Setup(m => m.ElementType).Returns(data2.ElementType);
objectInfo2.As<IQueryable<SomeObject1>>().Setup(m => m.GetEnumerator).Returns(data2.GetEnumerator);

this.mockDb.Setup(m => m.JunctionTable).Returns(objectInfo1.Object);
this.mockDb.Setup(m => m.ActualTable).Returns(objectInfo2.Object);

ClassName classData = new ClassName(this.mockDb.Object);
var result = classData.GetObjectByJunctionId(1);

Assert.AreEqual(1, result.Count);



So that's my test but I can't seem to have it pass.

Every time I get to the action for getting the object by an id, the query runs but the object is not found so the count is 0, so my Assert fails.

Any idea as to why?

Is This A Good Question/Topic? 0
  • +

Replies To: Unit Test Entity Framework with .Any

#2 andrewsw  Icon User is online

  • the case is sol-ved
  • member icon

Reputation: 6377
  • View blog
  • Posts: 25,768
  • Joined: 12-December 12

Re: Unit Test Entity Framework with .Any

Posted 06 October 2017 - 11:20 AM

What did you discover when debugging/ stepping through your code?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1