2
\$\begingroup\$

I have a method that gets an RSS feed using LINQ to XML and returns a collection of an object that grabs only the data I need. There's really only one other method in the class I'm concerned about that you'll see in the sample -- RemoveUrlNoise.

How do I test a method like this or change it to be more testable?

    public IEnumerable<PostDetails> GetPostDetails(string rssUrl)
    {
        XElement feed = XElement.Load(rssUrl);

        var items = from item in feed.Elements("channel").Elements("item") 
                    select item;

        return items.Select(item => new PostDetails
            {
                Title = item.Element("title").Value,
                Url = RemoveUrlNoise(item.Element("guid").Value),
                PubDate = item.Element("pubDate").Value
            }).OrderBy(i => i.PubDateAsDateTime).ToList(); 
    }
\$\endgroup\$
10
\$\begingroup\$

Separate the concerns of fetching the feed XML from parsing it by extracting a class (e.g. FeedReader) to do the reading. Your IFeedReader would be generically reusable and look something like:

public interface IFeedReader
{
    XElement Load(string url);
}

with implementation

public class FeedReader : IFeedReader
{
    public XElement Load(string url)
    {
        return XElement.Load(url);
    }
}

You then inject an IFeedReader through the constructor and use it to fetch the data in your method. This lets you use a Fake or a Mock of the IFeedReader, depending on your preference, to return appropriate results for your unit test.

consider reading up on: inversion of control (IoC) and dependency injection (DI), and mock object frameworks.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.