本文整理汇总了C#中Microsoft.VisualStudio.TestTools.UnitTesting.List.AsEnumerable方法的典型用法代码示例。如果您正苦于以下问题:C# List.AsEnumerable方法的具体用法?C# List.AsEnumerable怎么用?C# List.AsEnumerable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.VisualStudio.TestTools.UnitTesting.List
的用法示例。
在下文中一共展示了List.AsEnumerable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetAllVehicles
public void GetAllVehicles()
{
//Arrange
var data = new List<Vehicle>
{
new Vehicle {Name = "first"},
new Vehicle {Name = "second"}
};
var mockRep = new Mock<IRepository<Vehicle>>();
mockRep.Setup(x => x.GetAll()).Returns(data.AsEnumerable());
mockRep.Setup(x => x.Find(It.IsAny<Func<Vehicle, Boolean>>())).Returns(data.AsEnumerable());
var mockUnit = new Mock<IMotorDepotUnitOfWork>();
mockUnit.Setup(x => x.Vehicles).Returns(mockRep.Object);
var service = new VehicleService(mockUnit.Object);
Mapper.CreateMap<Vehicle, VehicleDTO>();
//Act
var result = service.GetVehicles().Count();
//Assert
mockRep.Verify(x => x.Find(It.IsAny<Func<Vehicle, Boolean>>()), Times.Once);
Assert.AreEqual(2, result);
}
示例2: ForEach_ListWithAction_ActionPerformedOnEachItemOfList
public void ForEach_ListWithAction_ActionPerformedOnEachItemOfList()
{
// Arrange
var toAdd = new Random().Next().ToString();
var list = new List<string> { "some", "random", "string", "items", "for", "test" };
var enumerable = list.AsEnumerable();
// Act
var final = new List<string>();
enumerable.ForEach(x => final.Add(x + toAdd));
// Assert
list.ForEach(x => final.Should().Contain(x + toAdd));
}
示例3: TestGetWithNSub
public void TestGetWithNSub()
{
var rtnForGetAll = new List<User>()
{
new User() { Name="Amigo", DepartmentId=1, Department=new Department() { Name="開發二課"} },
new User() { Name="Ariel", DepartmentId=1, Department=new Department() { Name="開發一課"} },
new User() { Name="Frank", DepartmentId=1, Department=new Department() { Name="開發一課"} }
};
IDalService dalService = Substitute.For<IDalService>();
dalService.GetAll().Returns(rtnForGetAll.AsEnumerable());
var entities = dalService.GetAll();
foreach (var entity in entities)
{
Debug.WriteLine(String.Format("Name:{0}, Department:{1}", entity.Name, entity.Department.Name));
}
Debug.WriteLine("Finish");
//The real test here ....
}
示例4: DataCalculator_Preview_ExceptOnTableValidation
public void DataCalculator_Preview_ExceptOnTableValidation()
{
var a = Rep.GetAccount(defAccountName, eagerLoad: new string[] { "Settings.Columns" });
if (a != null)
using (var dc = new DataCalculator(a, Rep))
{
var columns = string.Empty;
var colValues = a.Settings.Columns
.Where(c => c.ColumnType.ImportTableValidation)
.Select(c => c.ColumnName.ToLower())
.ToArray()
.Skip(1); //Skip one required row for take exception
foreach (var colName in colValues)
columns += (string.IsNullOrWhiteSpace(columns) ? string.Empty : ";") + colName;
var csvLines = new List<string>();
csvLines.Add(columns);
try
{
var l = Helpers.CSV.CSVFile.Load(csvLines.AsEnumerable<string>(),
tableName: "{virtual}",
filePath: "{virtual}",
tableValidator: dc.TableValidator,
rowFilter: dc.RowFilter);
}
catch(Exception ex)
{
var exText = ex.GetExceptionText();
Console.WriteLine(exText);
Assert.AreEqual(true, exText.Contains(colValues.First()), "Exception must contains required column name");
throw;
}
}
}
示例5: GetAllTasks_Valid_ReturnsCorrectTasks_Test
public void GetAllTasks_Valid_ReturnsCorrectTasks_Test()
{
// TODO add property values
//Arrange
var task1 = new StoredTaskRequest { Id = 0};
var task2 = new StoredTaskRequest { Id = 1};
var task3 = new StoredTaskRequest { Id = 2};
var taskList = new List<StoredTaskRequest> { task1, task2, task3 }.AsQueryable();
_repositoryMock.Setup(r => r.Read()).Returns(taskList);
var adapter = new TaskAdapter(_repositoryMock.Object);
//Act
var result = adapter.Read();
var actualTasks = result.ToList();
//Assert
var counter = 0;
foreach (var actualTask in taskList.AsEnumerable())
{
var returnedTask = actualTasks[counter];
// Todo add property asserts
Assert.IsTrue(returnedTask.Id == actualTask.Id);
counter++;
}
}
示例6: CheckLinesTest
//.........这里部分代码省略.........
* o o o o o o o o
* o o o o o o o o
*/
p = new Point(row, col++);
knownh.Add(p);
b.PlaceItem(p, 1);
result = b.CheckLines(p);
CollectionAssert.AreEquivalent(knownh, result);
/* o o + o o o o o
* o o + o o o o o
* + + + + + + + o
* o o + o o o o o
* o o + o o o o o
*/
knownv = new List<Point>();
for (row = 0, col = pc.Col, count = 0; count < 5; row++, count++)
{
p = new Point(row, col);
knownv.Add(p);
if (!p.Equals(pc))
b.PlaceItem(p, 1);
}
// from bottom
result = b.CheckLines(p);
CollectionAssert.AreEquivalent(knownv, result);
// from top
result = b.CheckLines(knownv.ElementAt(0));
CollectionAssert.AreEquivalent(knownv, result);
// two directions
known = new List<Point>();
known.AddRange(knownh.AsEnumerable());
known.AddRange(knownv.AsEnumerable());
// there is an extra point at the intersection
known.Remove(pc);
result = b.CheckLines(pc);
CollectionAssert.AreEquivalent(known, result);
/* o o + o o o o o
* o o + o o o o o
* + + + + + + + o
* o o + + o o o o
* o o + o + o o o
* o o o o o + o o
* o o o o o o + o
*/
knowndl = new List<Point>();
for (row = pc.Row, col = pc.Col, count = 0; count < 5; row++, col++, count++)
{
p = new Point(row, col);
knowndl.Add(p);
if (!p.Equals(pc))
b.PlaceItem(p, 1);
}
// from top left (second)
result = b.CheckLines(knowndl.ElementAt(1));
CollectionAssert.AreEquivalent(knowndl, result);
// from bottom right
result = b.CheckLines(knowndl.ElementAt(4));
CollectionAssert.AreEquivalent(knowndl, result);
// three directions
known.AddRange(knowndl.AsEnumerable());
示例7: GivenThatTenCharactersExists_WhenTryingToGetAll_ThenReturnedListContainsTenCharacters
public async Task GivenThatTenCharactersExists_WhenTryingToGetAll_ThenReturnedListContainsTenCharacters()
{
var charactersToReturn = new List<HouseEntity>();
for (int i = 0; i < 10; i++)
{
charactersToReturn.Add(new HouseEntity() { Id = i });
}
var repository = MockRepository.GenerateMock<IReadOnlyRepository<HouseEntity,int>>();
repository.Stub(x => x.GetAllAsync(CancellationToken.None,null))
.IgnoreArguments()
.Return(Task.FromResult(charactersToReturn.AsEnumerable()));
var service = new HouseService(repository);
var characters = await service.GetAllAsync();
Assert.IsNotNull(characters);
Assert.AreEqual(10, characters.Count());
}
示例8: GetAllUsers_Valid_ReturnsCorrectUsers_Test
public void GetAllUsers_Valid_ReturnsCorrectUsers_Test()
{
//Arrange
var user1 = new StoredUser {Name = "name1", MetaData = "metaData1"};
var user2 = new StoredUser {Name = "name2", MetaData = "metaData2"};
var user3 = new StoredUser {Name = "name3", MetaData = "metaData3"};
var list = new List<StoredUser> {user1, user2, user3}.AsQueryable();
_repositoryMock.Setup(r => r.Read()).Returns(list);
var adapter = new UserAdapter(_repositoryMock.Object);
//Act
var result = adapter.Read();
var actualUsers = result.ToList();
//Assert
var counter = 0;
foreach (var actualUser in list.AsEnumerable())
{
var returnedUser = actualUsers[counter];
Assert.IsTrue(returnedUser.Name == actualUser.Name);
Assert.IsTrue(returnedUser.MetaData == actualUser.MetaData);
Assert.IsTrue(returnedUser.Id == actualUser.Id);
counter++;
}
}
示例9: DataCalculator_Preview
//.........这里部分代码省略.........
var areaCol = acc.Settings.GetColumnFor(RoyaltyRepository.Models.ColumnTypes.Area);
var cityCol = acc.Settings.GetColumnFor(RoyaltyRepository.Models.ColumnTypes.City);
var cityHost = acc.Settings.GetColumnFor(RoyaltyRepository.Models.ColumnTypes.Host);
var cityPhone = acc.Settings.GetColumnFor(RoyaltyRepository.Models.ColumnTypes.Phone);
var csvLines = new List<string>();
var colValues = acc.Settings.Columns
.Where(c => c.ColumnType.ImportTableValidation)
.Select(c => new { Name = c.ColumnName.ToLower(), Type = c.ColumnType })
.ToArray();
var columns = string.Empty;
foreach (var colName in colValues)
columns += (string.IsNullOrWhiteSpace(columns) ? string.Empty : ";") + colName.Name;
csvLines.Add(columns);
var lastAddedPhone = string.Empty;
var genNewData = new Func<RoyaltyRepository.Models.ColumnTypes, string>(
(ct) =>
{
var res = string.Empty;
switch(ct)
{
case RoyaltyRepository.Models.ColumnTypes.Phone:
if (!string.IsNullOrWhiteSpace(lastAddedPhone) && rnd.Next(0, 5) == 0)
res = lastAddedPhone;
else
for (int n = 0; n < 5; n++)
res += rnd.Next(10, 99).ToString();
break;
case RoyaltyRepository.Models.ColumnTypes.Address:
res = streetNames.Union(new string[] { "defaultPreviewStreet2" }).ToArray()[rnd.Next(0, streetNames.Length + 1)]
+ ((rnd.Next(0, 5) != 0) ? ", " + rnd.Next(1,99) : string.Empty);
break;
case RoyaltyRepository.Models.ColumnTypes.Area:
res = areaNames.Union(new string[] { string.Empty, "defaultPreviewArea2" }).ToArray()[rnd.Next(0, areaNames.Length + 2)];
break;
case RoyaltyRepository.Models.ColumnTypes.City:
res = cityNames.Union(new string[] { "defaultPreviewCity1" }).ToArray()[rnd.Next(0, cityNames.Length + 1)];
break;
case RoyaltyRepository.Models.ColumnTypes.Host:
res = (rnd.Next(3) == 0 ? string.Empty : @"http://")
+ hostNames.Union(new string[] { "testhost2.ru" }).ToArray()[rnd.Next(0, hostNames.Length + 1)]
+ "/" + Guid.NewGuid().ToString("N");
break;
}
return res;
}
);
for (int i = 0; i < maxCnt; i++ )
{
columns = string.Empty;
foreach (var colName in colValues)
columns += (string.IsNullOrWhiteSpace(columns) ? string.Empty : ";") + genNewData(colName.Type.Type);
csvLines.Add(columns);
}
Rep.SaveChanges();
using (var dc = new DataCalculator(acc, Rep))
{
var prg0 = new Helpers.PercentageProgress();
var prg1 = prg0.GetChild();
var prg2 = prg0.GetChild();
var prg3 = prg0.GetChild();
prg0.Change += (s, e) => Helpers.Log.Add($"Progress: {e.Value.ToString("N2")}");
var log = new Action<string>((s) => Helpers.Log.Add(s));
var l = Helpers.CSV.CSVFile.Load(csvLines.AsEnumerable(),
tableValidator: dc.TableValidator,
rowFilter: dc.RowFilter);
dc.Prepare(l.Table, i => prg1.Value = i, log);
var previewRes = dc.Preview(l.Table, i => prg2.Value = i, log);
Assert.AreEqual(l.Table.Rows.Count, previewRes.Count());
var readyToExport = dc.Import(previewRes.Values, null, i => prg3.Value = i, log);
Rep.SaveChanges();
Helpers.Log.Add($"Data imported and ready to export");
Rep.AccountDataRecordRemove(acc.Data);
}
}
finally
{
hostNames.ToList().ForEach((s) =>
{
Rep.HostRemove(Rep.HostGet(s), saveAfterRemove: false);
});
cityNames.ToList().ForEach((s) =>
{
Rep.CityRemove(Rep.CityGet(s), saveAfterRemove: false);
});
Rep.SaveChanges();
SqlLogEnabled = true;
}
}
示例10: ListObjectTest
public void ListObjectTest()
{
MapFactory.ResetAllMaps();
var target = new List<InnType>
{
new InnType {DateTimeValue = DateTime.Now, DesimalValue = (decimal) 100.212, StringValue = "test"},
new InnType {DateTimeValue = DateTime.Now, DesimalValue = (decimal) 100.212, StringValue = "test"},
new InnType {DateTimeValue = DateTime.Now, DesimalValue = (decimal) 100.212, StringValue = "test"}
};
var map = MapFactory.CreateEmptyMapRule<InnType, OutType>();
map.AddMap<InnType, OutType>(new Dictionary<string, string>
{
{"DateTimeValue", "DateTimeValue1"},
{"DesimalValue", "DesimalValue1"},
{"StringValue", "StringValue1"}
});
var result = target.AsEnumerable().Map().To<OutType>(map);
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Count());
}
示例11: GetReverseMaps
IEnumerable<Tuple<int, int>> GetReverseMaps(int count)
{
var results = new List<Tuple<int, int>>();
for (int i = 0; i < count; i++)
{
results.Add(Tuple.Create(i, count - i - 1));
}
return results.AsEnumerable();
}
示例12: GetCustomerActiveAppointmentsPassed
public void GetCustomerActiveAppointmentsPassed()
{
//arrange
builder = new ContainerBuilder();
var eCancelWindow = generator.Generate<int>();
var eCustomerId = generator.Generate<int>();
var eDateTime = generator.Generate<DateTime>();
var eDesigner = generator.Generate<int>();
var eFee = generator.Generate<decimal>();
var eId = generator.Generate<int>();
var eSpcId = generator.Generate<int>();
List<IAppointmentData> lstAppts = new List<IAppointmentData>();
var appointmentData = new Mock<IAppointmentData>(MockBehavior.Strict);
appointmentData.SetupAllProperties();
appointmentData.SetupGet(_ => _.CancelWindow).Returns(eCancelWindow);
appointmentData.SetupGet(_ => _.CustomerId).Returns(eCustomerId);
appointmentData.SetupGet(_ => _.DateTime).Returns(eDateTime); ;
appointmentData.SetupGet(_ => _.DesignerId).Returns(eDesigner);
appointmentData.SetupGet(_ => _.Fee).Returns(eFee);
appointmentData.SetupGet(_ => _.Id).Returns(eId);
appointmentData.SetupGet(_ => _.SpecialtyId).Returns(eSpcId);
lstAppts.Add(appointmentData.Object);
var desgData = new Mock<IDesignerData>(MockBehavior.Strict);
desgData.SetupAllProperties();
desgData.SetupGet(_ => _.Id).Returns(generator.Generate<int>());
desgData.SetupGet(_ => _.Name).Returns(generator.Generate<string>());
var apptRepository = new Mock<IAppointmentRepository>(MockBehavior.Strict);
apptRepository.Setup(_ => _.GetCustomerActiveAppointments(It.IsAny<int>()))
.Returns(lstAppts.AsEnumerable());
var desgRepository = new Mock<IDesignerRepository>(MockBehavior.Strict);
desgRepository.Setup(_ => _.GetDesigner(It.IsAny<int>())).Returns(desgData.Object);
new MockTestBuilderComposition().Compose(builder);
builder.RegisterInstance(apptRepository.Object).As<IAppointmentRepository>();
builder.RegisterInstance(desgRepository.Object).As<IDesignerRepository>();
builder.RegisterType<MagenicMasters.CslaLab.Customer.AppointmentViewCollection>().As<MagenicMasters.CslaLab.Contracts.Customer.IAppointmentViewCollection>();
IoC.Container = builder.Build();
var activator = IoC.Container.Resolve<IDataPortalActivator>();
C.ApplicationContext.DataPortalActivator = IoC.Container.Resolve<IDataPortalActivator>();
//act
var objPortal = IoC.Container.Resolve<IObjectPortal<MagenicMasters.CslaLab.Contracts.Customer.IAppointmentViewCollection>>();
var apptViewColl = objPortal.Fetch(generator.Generate<int>());
//assert
Assert.IsNotNull(apptViewColl);
Assert.AreEqual(apptViewColl.First().StartDateTime, eDateTime);
Assert.AreEqual(apptViewColl.First().DesignerName, desgData.Object.Name);
}
示例13: GetAllProtocols_Valid_ReturnsCorrectProtocols_Test
public void GetAllProtocols_Valid_ReturnsCorrectProtocols_Test()
{
// TODO add property values
//Arrange
var protocol1 = new StoredProtocol {};
var protocol2 = new StoredProtocol {};
var protocol3 = new StoredProtocol {};
var protocolList = new List<StoredProtocol> { protocol1, protocol2, protocol3 }.AsQueryable();
_repositoryMock.Setup(r => r.Read()).Returns(protocolList);
var adapter = new ProtocolAdapter(_repositoryMock.Object);
//Act
var result = adapter.Read();
var actualProtocols = result.ToList();
//Assert
var counter = 0;
foreach (var actualProtocol in protocolList.AsEnumerable())
{
var returnedProtocol = actualProtocols[counter];
// Todo add property asserts
Assert.IsTrue(returnedProtocol.StudyName == actualProtocol.StudyName);
counter++;
}
}
示例14: DataCalculator_Prepare
public void DataCalculator_Prepare()
{
SqlLogEnabled = false;
try
{
var acc = Rep.GetAccount(defAccountName, eagerLoad: new string[] { "Settings.Columns.ColumnType" });
var csvLines = new List<string>();
var colValues = acc.Settings.Columns
.Where(c => c.ColumnType.ImportTableValidation)
.Select(c => new { Name = c.ColumnName.ToLower(), Type = c.ColumnType })
.ToArray();
var columns = string.Empty;
foreach (var colName in colValues)
columns += (string.IsNullOrWhiteSpace(columns) ? string.Empty : ";") + colName.Name;
columns += ";test_column";
csvLines.Add(columns);
using (var dc = new DataCalculator(acc, Rep))
{
var prg0 = new Helpers.PercentageProgress();
prg0.Change += (s, e) => Helpers.Log.Add($"Progress: {e.Value.ToString("N2")}");
var log = new Action<string>((s) => Helpers.Log.Add(s));
var l = Helpers.CSV.CSVFile.Load(csvLines.AsEnumerable(),
tableValidator: dc.TableValidator,
rowFilter: dc.RowFilter);
dc.Prepare(l.Table, i => prg0.Value = i, log);
Assert.AreEqual(true, acc.AdditionalColumns.Any(ad => ad.ColumnName == "test_column"));
Rep.SaveChanges();
Rep.AccountDataRecordAdditionalColumnRemove(acc.AdditionalColumns);
}
}
finally
{
SqlLogEnabled = true;
}
}
示例15: BugFix_InheritedInterfaceMethod
public void BugFix_InheritedInterfaceMethod()
{
var list = new List<int> { 123 };
var enumerator = list.AsEnumerable().GetEnumerator();
engine.AddRestrictedHostObject("enumerator", enumerator);
Assert.IsTrue((bool)engine.Evaluate("enumerator.MoveNext()"));
Assert.AreEqual(123, engine.Evaluate("enumerator.Current"));
Assert.IsFalse((bool)engine.Evaluate("enumerator.MoveNext()"));
engine.Execute("enumerator.Dispose()");
}