DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage
  • Observability Architecture: Financial Payments Introduction
  • RBAC With API Gateway and Open Policy Agent (OPA)
  • How to LINQ Between Java and SQL With JPAStreamer

Trending

  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage
  • Observability Architecture: Financial Payments Introduction
  • RBAC With API Gateway and Open Policy Agent (OPA)
  • How to LINQ Between Java and SQL With JPAStreamer
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Unit Testing File I/O Operations

Unit Testing File I/O Operations

Jeremy Jarrell user avatar by
Jeremy Jarrell
·
Mar. 13, 09 · News
Like (0)
Save
Tweet
Share
37.64K Views

Join the DZone community and get the full member experience.

Join For Free

This is an issue I’ve seen come up in my own team a lot lately and I thought it may be of general interest as well.  This issue is how would I unit test this class…

 

 

 

public class PointParser
{
private readonly StreamReader _streamReader;

public PointParser(string filePath)
{
_streamReader = new StreamReader(filePath);
}

public Point ReadPoint()
{
var coords = _streamReader.ReadLine().Split(new[] { ',' });
return new Point(Int32.Parse(coords[0]), Int32.Parse(coords[1]));
}
}

This class takes a path to a CSV file, opens the file, and then parses the coordinate values out of each line of the file into a series of points.  Let’s tackle the obvious first.  Anytime you can describe what a class does using the word “And” we’ve violated the Single Responsibility Principle so the class is doing too much.  Let’s simplify it a bit and let the class simply consume a file stream which has already been opened.  This way the class is not responsible for managing the stream resource and it can focus on what it does best…parsing the CSV file.

public class PointParser
{
private readonly StreamReader _streamReader;

public PointParser(StreamReader streamReader)
{
_streamReader = streamReader;
}

public Point ReadPoint()
{
var coords = _streamReader.ReadLine().Split(new[] { ',' });
return new Point(Int32.Parse(coords[0]), Int32.Parse(coords[1]));
}
}

Now we have a little bit more manageable problem.  Let’s think about a simile to this problem.  Imagine that instead of coming from a file, our points were coming from a database connection.

public PointParser(IDbConnection dbConnection)
{
_dbConnection = dbConnection;
}

Now this is something we can more easily recognize.  How would we test this?  Would we open a connection to live database that we’ve pre-populated with valid points?  Of course not, we would abstract the database connection out to a data source and then mock that data source for all of the database connections.  So, why wouldn’t we do the same here?

Moving from that example, we can see that we need to abstract out our StreamReader class.  BCL classes our notorious for being difficult to mock using anything other than TypeMock, but Microsoft threw us a bone here:  the StreamReader class actually derives from the TextReader class which is an abstract class.  And when it comes to mocking, at least, an abstract class is just as good as an interface.  So, our next step is to replace the reference to the concrete StreamReader class with it’s more flexible TextReader base class.   Now we have something we can work with.

public class PointParser
{
private readonly TextReader _textReader;

public PointParser(TextReader textReader)
{
_textReader = textReader;
}

public Point ReadPoint()
{
var coords = _textReader.ReadLine().Split(new[] { ',' });
return new Point(Int32.Parse(coords[0]), Int32.Parse(coords[1]));
}
}

So, using Rhino.Mocks, we can unit test this class all we like by simply simulating a stream of points…

[Test]
public void Can_get_the_first_line()
{
var textReader = MockRepository.GenerateMock<TextReader>();
textReader.Expect(tr => tr.ReadLine()).Return("50,100");

var pointParser = new PointParser(textReader);
var point = pointParser.ReadPoint();

Assert.AreEqual(new Point(50,100), point);
}

We can even generate error conditions

[Test]
[ExpectedException(typeof(InvalidPointException))]
public void Will_throw_an_error_if_point_is_invalid()
{
var textReader = MockRepository.GenerateMock<TextReader>();
textReader.Expect(tr => tr.ReadLine()).Return("50,Not_A_Number");

var pointParser = new PointParser(textReader);
var point = pointParser.ReadPoint();

Assert.AreEqual(new Point(50, 100), point);
}

So, to recap, here are the important points…

  • Any class that performs operations against the content of a file shouldn’t be responsible for also managing the connection to that file.
  • Your unit tests should only be concerned with how that class works with the content of the file, not the various conditions surrounding the connection.  Sure, you’ll want to also have tests in place to determine what happens when the file can’t be open because it’s already in use or isn’t at the location specified, but those are integration tests…not unit tests.
  • If you’re working with a StreamReader class, then you can abstract that up to a TextReader class and mock it.  If you’re of the FileStream persuasion, then you can abstract it up to a Stream.
unit test

Published at DZone with permission of Jeremy Jarrell. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • A Complete Guide to AWS File Handling and How It Is Revolutionizing Cloud Storage
  • Observability Architecture: Financial Payments Introduction
  • RBAC With API Gateway and Open Policy Agent (OPA)
  • How to LINQ Between Java and SQL With JPAStreamer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: