Archive for category c#
How To Reset Your SubSonic 3 ActiveRecord Test Repository For Each Unit Test
When writing unit tests with SubSonic’s new built-in testing for ActiveRecord don’t forget that each time you call the Setup() method on your ActiveRecord object it adds records to any that have already been created. For example:
[Test]
public void Foo_Bar() {
Foo.Setup(10);
Assert.AreEqual(10, Foo.All().Count());
}
[Test]
public void Bar_Foo() {
Foo.Setup(10);
// This will fail: Foo.All().Count() will return 20
Assert.AreEqual(10, Foo.All().Count());
}
To reset your test repositories you will need to call the ResetTestRepo() method prior to each test, which can be accomplished easily enough by adding the method call to your test’s [SetUp] method:
[SetUp]
public void SetUp() {
Foo.ResetTestRepo();
}
[Test]
public void Foo_Bar() {
Foo.Setup(10);
Assert.AreEqual(10, Foo.All().Count());
}
[Test]
public void Bar_Foo() {
Foo.Setup(10);
// Now Foo.All().Count() will return 10 and the test will pass
Assert.AreEqual(10, Foo.All().Count());
}
Hopefully this will save you a bit of time, as well as head scratching :p
C# String Extension Methods
There are quite a few instances where string operations in C# seem slightly verbose. So, I had a play around with extension methods the other day to see if I could come up with some alternate ways of doing some pretty standard operations but with a touch more syntactic sugar sprinkled on the top.
For example, rather than using string.IsNullOrEmpty it makes much more sense to me to call IsNullOrEmpty on the string you want to check instead:
// Checking for a null or empty string in C#
if (string.IsNullOrEmpty(foo)) {
...
}
// versus
if (foo.IsNullOrEmpty()) {
...
}
Also, I thought it would be nicer if you could call some of the static Regex methods directly on string objects:
// Instead of this
if (Regex.IsMatch(foo, @"[a-zA-Z]+")) {
...
}
// You could just do this
if (foo.IsMatch(@"[a-zA-Z]+")) {
...
}
I have created a gist of these methods, plus a few others:
Are there any other string operations that you think should be included? If you have any suggestions, etc. please be sure to comment.