Mocking HttpPostedFileBase InputStream with Rhino Mocks

I wanted to unit test a CSV file upload on a new website. I was using a standard file upload HTML input tag, which in .NET MVC translates into an HttpPostFileBase object. The main problem from the point of view of unit testing is that the InputStream method cannot be set directly, so I had to mock it (I use Rhino Mocks).

Here is my example method which can plugged into the test class. It converts a string into a stream and sets the view model’s UploadedFile property to that value. Just pass in the CSV string you wish to test. Note that you may need to change your Encoding method. Hopefully it will be useful in the future.

// The view model
public class MyViewModel
{
        [Required(ErrorMessage = "Please enter a file name")]
        public HttpPostedFileBase UploadedFile { get; set; }
}
// Creating the view model instance with the mocked input stream
private MyViewModel CreateInputModel(string input)
{
    MyViewModel passedModel = new MyViewModel();
    HttpPostedFileBase file = MockRepository.GenerateMock<HttpPostedFileBase>();
    string str = input ;
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
    MemoryStream stream = new MemoryStream(buffer);

    file.Stub(x => x.InputStream).Return(stream);
    passedModel.UploadedFile = file;
    return passedModel;
}
Advertisements

‘SELECT IN’ with fluent LINQ syntax

I like fluent syntax with lambda predicates, although I think introducing functional-programming style concepts does make C# a bit of a dog’s dinner of a language. There’s no denying it’s simple and easy to use though! However one thing I’ve always thought up until now is that if you want to mimic a ‘SELECT IN’ query then you’d have to build a dynamic where clause using something like this library from Scott Gu: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx.

However you don’t, it is actually quite simple. I’d known you could do this with non-fluent LINQ, but for some reason never twigged that you could do it fluently too. Here is the source, using SharpLite’s libraries to get some objects of type Entity from a table using an IRepository:


int[] toFind = {1, 4, 5, 34};
List<myEntity> entitiesToFind = new List<myEntity>();
// Effectively a 'Select In' - selecting all the entities with an entity ID in the selected list. 
entitiesToFind = _myRepository.GetAll().Where(x => toFind.Contains(x.Id)).ToList();