Skip to content

Instantly share code, notes, and snippets.

@christopherbauer
Created July 16, 2015 16:42
Show Gist options
  • Select an option

  • Save christopherbauer/9461384d357a1318d2c9 to your computer and use it in GitHub Desktop.

Select an option

Save christopherbauer/9461384d357a1318d2c9 to your computer and use it in GitHub Desktop.
SelectListFactory examples for blog
public interface ISelectable
{
string GetValueField();
string GetTextField();
}
public class SelectListFactory : ISelectListFactory
{
public SelectList Create<T>(IEnumerable<T> listOfT) where T : ISelectable
{
var selectListItems = listOfT.Select(arg => new SelectListItem
{
Text = arg.GetTextField(),
Value = arg.GetValueField()
});
return new SelectList(selectListItems.ToList(), "Value", "Text");
}
}
internal class SelectListFactoryTests
{
[TestFixture]
public class when_creating_a_select_List_factory_with_funcs
{
public class TestSelectable : ISelectable
{
public string GetValueField()
{
return "Value";
}
public string GetTextField()
{
return "Test";
}
}
[Test]
public void then_should_use_text_field_of_test_selectable()
{
// Arrange
var factory = new SelectListFactory();
// Act
var selectList = factory.Create(new List<TestSelectable> {new TestSelectable()});
// Assert
Assert.That(selectList.All(item => item.Text == "Test"), Is.True);
}
[Test]
public void then_should_use_value_field_of_test_selectable()
{
// Arrange
var factory = new SelectListFactory();
// Act
var selectList = factory.Create(new List<TestSelectable> {new TestSelectable()});
// Assert
Assert.That(selectList.All(item => item.Value == "Value"), Is.True);
}
[Test]
public void then_should_throw_exception_given_null_list_of_items()
{
// Arrange
var factory = new SelectListFactory();
// Act // Assert
Assert.Throws<ArgumentNullException>(() => factory.Create((List<TestSelectable>) null));
}
}
}
public class SelectListFactory : ISelectListFactory
{
public SelectList CreateSelectList<T>(IEnumerable<T> items, string dataValueProperty, string dataTextProperty)
{
return new SelectList(items, dataValueProperty, dataTextProperty);
}
public SelectList CreateSelectList<T>(IEnumerable<T> items, Func<T, object> valueExpression, Func<T, object> textExpression)
{
return CreateSelectList(items, valueExpression, textExpression, null);
}
public SelectList CreateSelectList<T>(IEnumerable<T> items, Func<T, object> valueExpression,
Func<T, object> textExpression, object selectedValue)
{
var enumerable = items.Select(item => new SelectListItem
{
Text = textExpression.Invoke(item).ToString(),
Value = valueExpression.Invoke(item).ToString(),
});
return new SelectList(enumerable.ToList(), "Value", "Text", selectedValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment