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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot

Trending

  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • MCP Servers: The Technical Debt That Is Coming
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  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

By 
Jeremy Jarrell user avatar
Jeremy Jarrell
·
Mar. 13, 09 · News
Likes (0)
Comment
Save
Tweet
Share
38.8K 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.

Related

  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!