Long time ago I’ve created a project which purpose is to teach LINQ using tests. Technically it’s not exacly TDD. I’d rather call it TDL (test-driven learning), an “invention” of my own ;)
Before we start let me point you to source code located on my GitHub repository.
The basics of LINQ are fairly easy. We have to learn how to filter, sort and project data. It can be used in two ways: the method syntax and the query syntax. This can feel weird in the beginning. Method syntax is my prefered way of using LINQ. I also think that LINQ newbies should start with it.
Whereas you can start learning it by building database and using ORM technology like Entity Framework, I’d rather advise you to start with simple lists (
The Test-Driven Learning approach
TDL works almost like TDD, but with few differences. I’ve created a series of unit tests. Except for a “starter” test they are all “red”, which means that they all fail. Your job is to make them pass.
Each test is prefilled and described in such a way that you know which method you should use. It also operates on precreated datasets (arrays of data), so you know what should be the result (and the test “know” when to fail).
For a student it’s nothing more than just using a correct method to make the test pass. It has a kind of “bonus”. You’re learning LINQ, but at the same time you’re getting familiar with unit testing and unit testing framework. You can say it’s a “two for a price of one” thing.
Let’s sum up test-driven learning principles:
- learning is guided by tests
- tests are created beforehand
- each test compiles correctly, but it does not pass
- every test operates on a precreated dataset, which should not be altered
- each test defines which method should be used to “solve” it
- every test defines what result is expected (by the asserts used to verify if provided solution is correct)
- student is expected to update the code in such a way that tests will pass; she/he cannot alter datasets nor asserts
Using tests to learn LINQ
Now that you know how TDL works let me show you how it’s implemented in my solution (linq-exercises source code).
Let’s take a look at one of the tests:
As you can see you need to fetch first string having 4 letters. It uses
TestData.Animals list as data source. It also expects you to use
First method. Because of the assert we also know that it should return
Now, once you take a look at the documentation, you notice that there’s an overloaded version of
First, which we can use to find first record matching certain criteria. You update the test and make it pass:
What do you think about this method of learning/teaching? Let me know in the comments.