views:

15

answers:

0

So I have a little app which will process a load of files and I'm trying to write tests for the class which will handle looping through the files and firing them to various places. This was an obvious place to try out the new parallel library stuff. Heres a simplified version of the code I'm testing:

public void ProcessSomeFiles(IEnumerable<string> FilePaths)
    {
        Parallel.ForEach(FilePaths, FilePath =>
        {
            ILogWriter oLogWriter = ComponentLoader.GetILogWriter();
            IFileLoader oFileLoader = ComponentLoader.GetIFileLoader();

            XmlDocument oDoc;
            try
            {
                oDoc = oFileLoader.LoadFile(FilePath);
            }
            catch (XmlException)
            {
                oLogWriter.WriteLogEntry(new LogEntry(DateTime.Now, 4, "FileProcessor", "File Load Exception", "'" + FilePath + "': File was not valid XML"));
                return;
            }

            // More logic here
        });
    }

Simple change to make it run in parallel, cool. The LogWriter and FileLoader are being brought in from a little custom IOC container called ComponentLoader. Next was the tests, which just seem to crash no matter what I do. Heres what I have at the moment:

MockRepository oRepository = new MockRepository();

IFileLoader oFileLoader1 = oRepository.StrictMock<IFileLoader>();
Expect.Call(oFileLoader1.LoadFile("File1.xml")).Return(new XmlDocument());

IFileLoader oFileLoader2 = oRepository.StrictMock<IFileLoader>();
Expect.Call(oFileLoader2.LoadFile("File2.xml")).Return(new XmlDocument());

ILogWriter oLogWriter1 = oRepository.StrictMock<ILogWriter>();
Expect.Call(() => oLogWriter1.WriteLogEntry(new LogEntry(DateTime.Now, 5, "FileProcessor", "Successful Load", "File1.xml")));

ILogWriter oLogWriter2 = oRepository.StrictMock<ILogWriter>();
Expect.Call(() => oLogWriter2.WriteLogEntry(new LogEntry(DateTime.Now, 5, "FileProcessor", "Successful Load", "File2.xml")));

IComponentLoader oComponentLoader = oRepository.StrictMock<IComponentLoader>();
Expect.Call(oComponentLoader.GetIFileLoader()).Return(oFileLoader1);
Expect.Call(oComponentLoader.GetIFileLoader()).Return(oFileLoader2);
Expect.Call(oComponentLoader.GetILogWriter()).Return(oLogWriter1);
Expect.Call(oComponentLoader.GetILogWriter()).Return(oLogWriter2);

oRepository.ReplayAll();

FileProcessor oProcessor = new FileProcessor(oComponentLoader);

oProcessor.ProcessSomeFiles(new List<string> { "File1.xml", "File2.xml" });

oRepository.VerifyAll();

First issue, the test isn't able to check which order the loop is running in, so I can see it failing if the parallel loop runs 2 before 1. Second, when I run it in either resharper or the VS test runner it sits there forever processing. I'm assuming its some locking issue but I'm quite new to threading so...

Hopefully one of you will be able to tell me I'm being stupid and approaching this in totally the wrong way?

Thanks