本文整理汇总了C#中Mock.As方法的典型用法代码示例。如果您正苦于以下问题:C# Mock.As方法的具体用法?C# Mock.As怎么用?C# Mock.As使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mock
的用法示例。
在下文中一共展示了Mock.As方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ActionFilter_SettingResult_ShortCircuits
// This is used as a 'common' test method for ActionFilterAttribute and Controller
public static async Task ActionFilter_SettingResult_ShortCircuits(Mock mock)
{
// Arrange
mock.As<IAsyncActionFilter>()
.Setup(f => f.OnActionExecutionAsync(
It.IsAny<ActionExecutingContext>(),
It.IsAny<ActionExecutionDelegate>()))
.CallBase();
mock.As<IActionFilter>()
.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()))
.Callback<ActionExecutingContext>(c =>
{
mock.ToString();
c.Result = new NoOpResult();
});
mock.As<IActionFilter>()
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Verifiable();
var context = CreateActionExecutingContext(mock.As<IFilter>().Object);
var next = new ActionExecutionDelegate(() => { throw null; }); // This won't run
// Act
await mock.As<IAsyncActionFilter>().Object.OnActionExecutionAsync(context, next);
// Assert
Assert.IsType<NoOpResult>(context.Result);
mock.As<IActionFilter>()
.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Never());
}
示例2: GetAllShouldReturnTodos
public void GetAllShouldReturnTodos()
{
var data = new List<Todo>
{
new Todo {Id = 1},
new Todo {Id = 2},
new Todo {Id = 3},
}.AsQueryable();
var mockSet = new Mock<DbSet<Todo>>();
mockSet.As<IQueryable<Todo>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Todo>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Todo>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Todo>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var mockContext = new Mock<ApplicationDbContext>();
mockContext.Setup(c => c.Todos).Returns(mockSet.Object);
var service = new TodoRepository(mockContext.Object);
var todos = service.GetAll().ToList();
Assert.AreEqual(3, todos.Count);
Assert.AreEqual(1, todos[0].Id);
Assert.AreEqual(2, todos[1].Id);
Assert.AreEqual(3, todos[2].Id);
}
示例3: PersonService_GetAsync_ReturnsPersons
public void PersonService_GetAsync_ReturnsPersons()
{
//Arrange
var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>();
var mockDbContextScope = new Mock<IDbContextReadOnlyScope>();
var mockEfDbContext = new Mock<EFDbContext>();
mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object);
mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object);
var mockAppUserManager = new Mock<IAppUserManager>();
var mockDbUserService = new Mock<DBUserService>(new object[] {mockDbContextScopeFac.Object, mockAppUserManager.Object, true });
var dbEntry1 = new Person { Id = "dummyEntryId1", FirstName = "First1", LastName = "Last1", IsActive_bl = false, Initials = "FLA1" };
var dbEntry2 = new Person { Id = "dummyEntryId2", FirstName = "First2", LastName = "Last2", IsActive_bl = true, Initials = "FLA2" };
var dbEntries = (new List<Person> { dbEntry1, dbEntry2 }).AsQueryable();
var mockDbSet = new Mock<DbSet<Person>>();
mockDbSet.As<IDbAsyncEnumerable<Person>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<Person>(dbEntries.GetEnumerator()));
mockDbSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<Person>(dbEntries.Provider));
mockDbSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(dbEntries.Expression);
mockDbSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType);
mockDbSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator());
mockEfDbContext.Setup(x => x.Persons).Returns(mockDbSet.Object);
var personService = new PersonService(mockDbContextScopeFac.Object, "DummyUserId");
//Act
var resultPersons = personService.GetAllAsync().Result;
//Assert
Assert.IsTrue(resultPersons.Count == 1);
Assert.IsTrue(resultPersons[0].LastName.Contains("Last2"));
}
示例4: InitializeContext
public void InitializeContext()
{
var elementInfo1 = Mocks.Of<IElementInfo>().First(i => i.Name == "FooElementName" && i.DisplayName == "FooElementNameDisplayName");
var element1 = new Mock<IElement>();
element1.SetupGet(e => e.Info).Returns(elementInfo1);
element1.As<IAbstractElement>().SetupGet(e => e.Info).Returns(elementInfo1);
element1.As<IProductElement>().SetupGet(e => e.Info).Returns(elementInfo1);
var elementInfo2 = Mocks.Of<IElementInfo>().First(i => i.Name == "BarElementName" && i.DisplayName == "BarElementNameDisplayName");
var element2 = new Mock<IElement>();
element2.Setup(e => e.InstanceName).Returns("FooElement2NameDisplayName");
element2.SetupGet(e => e.Info).Returns(elementInfo2);
element2.As<IAbstractElement>().SetupGet(e => e.Info).Returns(elementInfo2);
element2.As<IProductElement>().SetupGet(e => e.Info).Returns(elementInfo2);
var viewInfo = new Mock<IViewInfo>();
viewInfo.SetupGet(v => v.Elements).Returns(new[] { elementInfo1, elementInfo2 });
var view = new Mock<IView>();
view.SetupGet(v => v.Info).Returns(viewInfo.Object);
view.SetupGet(v => v.Elements).Returns(new[] { element1.Object, element2.Object });
var productInfo = new Mock<IPatternInfo>();
productInfo.SetupGet(pi => pi.Name).Returns("FooProductName");
productInfo.SetupGet(pi => pi.Views).Returns(new[] { viewInfo.Object });
var product = new Mock<IProduct>();
product.Setup(p => p.InstanceName).Returns("TestProduct");
product.As<IProduct>().SetupGet(p => p.Info).Returns(productInfo.Object);
product.As<IProductElement>().SetupGet(p => p.Info).Returns(productInfo.Object);
product.SetupGet(p => p.Views).Returns(new[] { view.Object });
this.rule = new CardinalityValidationRule();
this.rule.CurrentElement = product.Object;
}
示例5: Index
public void Index()
{
// DBのモックを用意する
var mockset = new Mock<DbSet<BoardEntity>>();
var mockcontext = new Mock<BoardDbContext>();
var originalData = new List<BoardEntity> {
new BoardEntity { Id = 1, Title = "A", Text = "a" },
new BoardEntity { Id = 2, Title = "B", Text = "b" },
new BoardEntity { Id = 3, Title = "C", Text = "c" },
};
var data = originalData.AsQueryable();
// 各メソッドの返り値をモックに差し替える
mockset.As<IQueryable<BoardEntity>>().Setup( m => m.Provider ).Returns( data.Provider );
mockset.As<IQueryable<BoardEntity>>().Setup( m => m.Expression ).Returns( data.Expression );
mockset.As<IQueryable<BoardEntity>>().Setup( m => m.ElementType ).Returns( data.ElementType );
mockset.As<IQueryable<BoardEntity>>().Setup( m => m.GetEnumerator() ).Returns( data.GetEnumerator() );
mockcontext.Setup( m => m.Boards ).Returns( mockset.Object );
var controller = new BoardController( mockcontext.Object );
ViewResult result = controller.Index() as ViewResult;
// モデルのデータがちゃんとDBのデータを取得出来ているか検証
var model = result.Model as BoardListModel;
Assert.AreSame( originalData[0], model.Boards[0] );
Assert.AreSame( originalData[1], model.Boards[1] );
Assert.AreSame( originalData[2], model.Boards[2] );
Assert.IsNotNull( result );
}
示例6: TestCacheableGetAllProductsSync
public void TestCacheableGetAllProductsSync()
{
var data = new List<Product>
{
new Product { ProductName = "BBB"},
new Product { ProductName = "ZZZ" },
new Product { ProductName = "AAA" }
}.AsQueryable();
var mockSet = new Mock<DbSet<Product>>();
mockSet.As<IQueryable<Product>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Product>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Product>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Product>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var mockContext = new Mock<SampleContext>();
mockContext.Setup(c => c.Products).Returns(mockSet.Object);
// public List<Product> GetAllProductsOrderedByName()
var products = mockContext.Object.Products
.OrderBy(product => product.ProductName)
.Cacheable()
.ToList();
Assert.AreEqual(3, products.Count);
Assert.AreEqual("AAA", products[0].ProductName);
Assert.AreEqual("BBB", products[1].ProductName);
Assert.AreEqual("ZZZ", products[2].ProductName);
}
示例7: TestPatientsAndAppointments
/// <summary>
/// Tests patient and appointment lists.
/// </summary>
/// <param name="appts">List of appointments to substitute in our mockup.</param>
/// <param name="patients">List of patients to substitute in our mockup.</param>
/// <param name="compare_date">The date to compare in our mockup.</param>
/// <returns></returns>
private static IEnumerable<Transaction> TestPatientsAndAppointments(
List<appointment_data> appts,
List<patient_data> patients,
DateTime compare_date)
{
var mock_appts = new Mock<DbSet<appointment_data>>();
mock_appts.As<IQueryable<appointment_data>>().Setup(m => m.Provider)
.Returns(appts.AsQueryable<appointment_data>().Provider);
mock_appts.As<IQueryable<appointment_data>>().Setup(m => m.Expression)
.Returns(appts.AsQueryable<appointment_data>().Expression);
mock_appts.As<IQueryable<appointment_data>>().Setup(m => m.ElementType)
.Returns(appts.AsQueryable<appointment_data>().ElementType);
mock_appts.As<IQueryable<appointment_data>>().Setup(m => m.GetEnumerator())
.Returns(appts.AsQueryable<appointment_data>().GetEnumerator());
var mock_patients = new Mock<DbSet<patient_data>>();
mock_patients.As<IQueryable<patient_data>>().Setup(m => m.Provider)
.Returns(patients.AsQueryable<patient_data>().Provider);
mock_patients.As<IQueryable<patient_data>>().Setup(m => m.Expression)
.Returns(patients.AsQueryable<patient_data>().Expression);
mock_patients.As<IQueryable<patient_data>>().Setup(m => m.ElementType)
.Returns(patients.AsQueryable<patient_data>().ElementType);
mock_patients.As<IQueryable<patient_data>>().Setup(m => m.GetEnumerator())
.Returns(patients.AsQueryable<patient_data>().GetEnumerator());
var fake_entities = new Mock<broadlyEntities>();
fake_entities.Setup(c => c.appointment_data).Returns(mock_appts.Object);
fake_entities.Setup(c => c.patient_data).Returns(mock_patients.Object);
IEnumerable<Transaction> transactions = DataSource.GetTransactions(compare_date, fake_entities.Object);
Assert.IsNotNull(transactions);
Assert.IsTrue(transactions is IQueryable);
Assert.IsTrue(transactions is IQueryable<Transaction>);
foreach (Transaction transaction in transactions)
{
// There is an email
Assert.IsTrue(!string.IsNullOrEmpty(transaction.PatientEmail));
// The appoinment time matches
Assert.IsTrue(transaction.AppointmentTime == compare_date);
// There is a transaction with this Id
appointment_data appt = appts.Find(x => x.appointment_id == transaction.AppointmentId);
Assert.IsNotNull(appt);
// There is a patient with the appt's Id
patient_data patient = patients.Find(x => x.patient_id == appt.patient_id);
Assert.IsNotNull(patient);
// Check content
Assert.IsTrue(transaction.AppointmentId == appt.appointment_id);
Assert.IsTrue(transaction.AppointmentTime == appt.scheduled);
Assert.IsTrue(appt.status == "completed");
Assert.IsTrue(transaction.PatientFirstName == patient.first_name);
Assert.IsTrue(transaction.PatientLastName == patient.last_name);
Assert.IsTrue(transaction.PatientId == patient.patient_id);
Assert.IsTrue(transaction.PatientPhone == patient.phone);
}
return transactions;
}
示例8: GetKraniumAsyncTest
public async Task GetKraniumAsyncTest()
{
var kraniumsMockedList = new List<KraniumEntity>
{
new KraniumEntity { Name = "TheKranium", IPAddress = "192.168.0.50" },
//new Kranium { Name = "TheBackupKranium", IPAddress = "192.168.0.51" },
}.AsQueryable();
var mockSet = new Mock<DbSet<KraniumEntity>>();
mockSet.As<IDbAsyncEnumerable<KraniumEntity>>()
.Setup(m => m.GetAsyncEnumerator())
.Returns(new TestDbAsyncEnumerator<KraniumEntity>(kraniumsMockedList.GetEnumerator()));
mockSet.As<IQueryable<KraniumEntity>>()
.Setup(m => m.Provider)
.Returns(new TestDbAsyncQueryProvider<KraniumEntity>(kraniumsMockedList.Provider));
mockSet.As<IQueryable<KraniumEntity>>().Setup(m => m.Expression).Returns(kraniumsMockedList.Expression);
mockSet.As<IQueryable<KraniumEntity>>().Setup(m => m.ElementType).Returns(kraniumsMockedList.ElementType);
mockSet.As<IQueryable<KraniumEntity>>().Setup(m => m.GetEnumerator()).Returns(kraniumsMockedList.GetEnumerator());
var mockContext = new Mock<IKraniumDbContext>();
mockContext.Setup(c => c.Kranium).Returns(mockSet.Object);
var repository = new EfKraniumRepository { Context = mockContext.Object };
var kranium = await repository.GetKraniumAsync();
Assert.IsNotNull(kranium);
Assert.AreEqual("TheKranium", kranium.Name);
Assert.AreEqual("192.168.0.50", kranium.IPAddress);
}
示例9: GetApplicationDbContextMock
private Mock<ApplicationDbContext> GetApplicationDbContextMock()
{
// single user
var appUser = new ApplicationUser();
appUser.Id = "1";
var data = new List<ToDo> {
new ToDo { Id = 0, Title = "Todo 1", Completed = false, User = appUser },
new ToDo { Id = 1, Title = "Todo 2", Completed = true, User = appUser },
}.AsQueryable();
var mockSet = new Mock<DbSet<ToDo>>();
mockSet.As<IDbAsyncEnumerable<ToDo>>()
.Setup(m => m.GetAsyncEnumerator())
.Returns(new TestDbAsyncEnumerator<ToDo>(data.GetEnumerator()));
mockSet.As<IQueryable<ToDo>>()
.Setup(m => m.Provider)
.Returns(new TestDbAsyncQueryProvider<ToDo>(data.Provider));
mockSet.As<IQueryable<ToDo>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<ToDo>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<ToDo>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var applicationDbContext = new Mock<ApplicationDbContext>();
applicationDbContext.Setup(c => c.ToDos).Returns(mockSet.Object);
return applicationDbContext;
}
示例10: DeberiActualizar
public void DeberiActualizar()
{
var mockSet = new Mock<DbSet<Student>>();
var mockContext = new Mock<UniversityContext>();
mockContext.Setup(m => m.Students).Returns(mockSet.Object);
var existing = new Student { StudentId = 1, Nombre = "Carlos", Paterno = "Estrada", Materno = "Copa", Telefono = 2269587 };
var data = new Student
{
StudentId = 1,
Nombre = "Carlos",
Paterno = "Estrada",
Materno = "Copa",
Telefono = 2269587,
};
var queryable = new List<Student> { data }.AsQueryable();
mockSet.As<IQueryable<Student>>().Setup(m => m.Provider).Returns(queryable.Provider);
mockSet.As<IQueryable<Student>>().Setup(m => m.Expression).Returns(queryable.Expression);
mockSet.As<IQueryable<Student>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
mockSet.As<IQueryable<Student>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
mockContext.Setup(m => m.SaveChanges()).Verifiable();
var service = new UniversityContextService(mockContext.Object);
service.UpdateStudent(data);
var mostrar = service.Show();
mockContext.Verify();
Assert.AreEqual(1, mostrar.Count);
Assert.AreEqual("Carlos", mostrar[0].Nombre);
Assert.AreEqual(2269587, mostrar[0].Telefono);
}
示例11: Handler_ReturnsFalse_WhenUserExists_ButHasDifferentPassword
public void Handler_ReturnsFalse_WhenUserExists_ButHasDifferentPassword()
{
string nameOrVerifiedEmail = FakeData.Email();
string password = FakeData.String();
var user = new User { Name = nameOrVerifiedEmail, };
var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
Expression<Func<UserByNameOrVerifiedEmail, bool>> expectedQuery =
x => x.NameOrEmail == nameOrVerifiedEmail;
queries.Setup(x => x.Execute(It.Is(expectedQuery)))
.Returns(Task.FromResult(user));
var userStore = new Mock<IUserStore<User, int>>(MockBehavior.Strict);
userStore.Setup(x => x.FindByNameAsync(nameOrVerifiedEmail)).Returns(Task.FromResult(user));
var passwordHasher = new PasswordHasher();
Expression<Func<User, bool>> expectedUser = x => x.Name == nameOrVerifiedEmail;
userStore.As<IUserPasswordStore<User, int>>().Setup(x => x.GetPasswordHashAsync(It.Is(expectedUser)))
.Returns(Task.FromResult(passwordHasher.HashPassword(FakeData.String())));
var userManager = new UserManager<User, int>(userStore.Object);
var handler = new HandleIsPasswordVerifiedQuery(queries.Object, userManager);
var query = new IsPasswordVerified
{
UserNameOrVerifiedEmail = nameOrVerifiedEmail,
Password = password,
};
bool result = handler.Handle(query).Result;
result.ShouldBeFalse();
queries.Verify(x => x.Execute(It.Is(expectedQuery)), Times.Once());
userStore.Verify(x => x.FindByNameAsync(nameOrVerifiedEmail), Times.Once);
userStore.As<IUserPasswordStore<User, int>>().Verify(
x => x.GetPasswordHashAsync(It.Is(expectedUser)), Times.Once);
}
示例12: ComponentStatusService_GetAsync_ReturnsComponentStatuss
public void ComponentStatusService_GetAsync_ReturnsComponentStatuss()
{
//Arrange
var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>();
var mockDbContextScope = new Mock<IDbContextReadOnlyScope>();
var mockEfDbContext = new Mock<EFDbContext>();
mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object);
mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object);
var dbEntry1 = new ComponentStatus { Id = "dummyEntryId1", CompStatusName = "Name1", CompStatusAltName = "NameAlt1", IsActive_bl = false, Comments = "DummyComments1" };
var dbEntry2 = new ComponentStatus { Id = "dummyEntryId2", CompStatusName = "Name2", CompStatusAltName = "NameAlt2", IsActive_bl = true, Comments = "DummyComments2" };
var dbEntries = (new List<ComponentStatus> { dbEntry1, dbEntry2 }).AsQueryable();
var mockDbSet = new Mock<DbSet<ComponentStatus>>();
mockDbSet.As<IDbAsyncEnumerable<ComponentStatus>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<ComponentStatus>(dbEntries.GetEnumerator()));
mockDbSet.As<IQueryable<ComponentStatus>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<ComponentStatus>(dbEntries.Provider));
mockDbSet.As<IQueryable<ComponentStatus>>().Setup(m => m.Expression).Returns(dbEntries.Expression);
mockDbSet.As<IQueryable<ComponentStatus>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType);
mockDbSet.As<IQueryable<ComponentStatus>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator());
mockDbSet.Setup(x => x.Include(It.IsAny<string>())).Returns(mockDbSet.Object);
mockEfDbContext.Setup(x => x.ComponentStatuss).Returns(mockDbSet.Object);
var compStatusService = new ComponentStatusService(mockDbContextScopeFac.Object,"DummyUserId");
//Act
var resultComponentStatuss = compStatusService.GetAsync().Result;
//Assert
Assert.IsTrue(resultComponentStatuss.Count == 1);
Assert.IsTrue(resultComponentStatuss[0].CompStatusAltName.Contains("NameAlt2"));
}
示例13: ReturnsPostsThatHavePublishedSetToTrue_AndPostedDateDesc
public void ReturnsPostsThatHavePublishedSetToTrue_AndPostedDateDesc()
{
var posts = new List<Post>
{
new Post {Id = 1, PostedOn = DateTime.Now.AddDays(-2), Published = true},
new Post {Id = 2, PostedOn = DateTime.Now.AddDays(-1), Published = false},
new Post {Id = 3, PostedOn = DateTime.Now, Published = true},
}.AsQueryable();
var mockPosts = new Mock<DbSet<Post>>();
mockPosts.As<IQueryable<Post>>().Setup(m => m.Provider).Returns(posts.Provider);
mockPosts.As<IQueryable<Post>>().Setup(m => m.Expression).Returns(posts.Expression);
mockPosts.As<IQueryable<Post>>().Setup(m => m.ElementType).Returns(posts.ElementType);
mockPosts.As<IQueryable<Post>>().Setup(m => m.GetEnumerator()).Returns(posts.GetEnumerator());
var expected = mockPosts.Object.Where(x => x.Published).OrderByDescending(x => x.PostedOn).ToList();
_slapdashContext
.Setup(x => x.Posts)
.Returns(mockPosts.Object);
var actual = _classUnderTest.Posts(1, 1);
Assert.Equal(expected, actual);
}
示例14: ProjectService_GetAsync_ReturnsProjects
public void ProjectService_GetAsync_ReturnsProjects()
{
//Arrange
var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>();
var mockDbContextScope = new Mock<IDbContextReadOnlyScope>();
var mockEfDbContext = new Mock<EFDbContext>();
mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object);
mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object);
var dbEntry1 = new Project { Id = "dummyEntryId1", ProjectName = "Project1", ProjectAltName = "ProjectAlt1", IsActive_bl = false, ProjectCode = "CODE1" };
var dbEntry2 = new Project { Id = "dummyEntryId2", ProjectName = "Project2", ProjectAltName = "ProjectAlt2", IsActive_bl = true, ProjectCode = "CODE2" };
var dbEntries = (new List<Project> { dbEntry1, dbEntry2 }).AsQueryable();
var mockDbSet = new Mock<DbSet<Project>>();
mockDbSet.As<IDbAsyncEnumerable<Project>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<Project>(dbEntries.GetEnumerator()));
mockDbSet.As<IQueryable<Project>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<Project>(dbEntries.Provider));
mockDbSet.As<IQueryable<Project>>().Setup(m => m.Expression).Returns(dbEntries.Expression);
mockDbSet.As<IQueryable<Project>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType);
mockDbSet.As<IQueryable<Project>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator());
mockDbSet.Setup(x => x.Include(It.IsAny<string>())).Returns(mockDbSet.Object);
mockEfDbContext.Setup(x => x.Projects).Returns(mockDbSet.Object);
var projectService = new ProjectService(mockDbContextScopeFac.Object, "dummyUserId");
//Act
var resultProjects = projectService.GetAsync().Result;
//Assert
Assert.IsTrue(resultProjects.Count == 1);
Assert.IsTrue(resultProjects[0].ProjectAltName.Contains("ProjectAlt2"));
}
示例15: generateSensorDataSet
private legion_service_api generateSensorDataSet()
{
Random rnd = new Random();
IQueryable<sensor_data> data = new List<sensor_data>
{
new sensor_data { Id = 1, userGuid = "teste.teste.teste", sensor_name = "sensor1", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))},
new sensor_data { Id = 3, userGuid = "teste.teste.teste", sensor_name = "sensor2", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))},
new sensor_data { Id = 4, userGuid = "teste.teste.teste", sensor_name = "sensor2", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))},
new sensor_data { Id = 5, userGuid = "teste.teste.teste", sensor_name = "sensor3", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))},
new sensor_data { Id = 6, userGuid = "teste.teste.teste2", sensor_name = "sensor2", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))},
new sensor_data { Id = 7, userGuid = "teste.teste.teste2", sensor_name = "sensor2", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))},
new sensor_data { Id = 2, userGuid = "teste.teste.teste2", sensor_name = "sensor1", timestamp = DateTime.Now.AddMilliseconds(rnd.Next(1000, 10000))}
}.AsQueryable();
var mockset = new Mock<DbSet<sensor_data>>();
mockset.As<IQueryable<sensor_data>>().Setup(m => m.Provider).Returns(data.Provider);
mockset.As<IQueryable<sensor_data>>().Setup(m => m.Expression).Returns(data.Expression);
mockset.As<IQueryable<sensor_data>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockset.As<IQueryable<sensor_data>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var mockContext = new Mock<legion_serviceContext>();
mockContext.Setup(s => s.sensor_data).Returns(mockset.Object);
return new legion_service_api(mockContext.Object);
}