Category Archives: C#

Mocks versus stubs and fakes

I dislike using mocks I dislike using dynamic mocking/stubbing frameworks. because it means my tests have an extra dependency beyond just the SUT (System Under Test). I often find myself spending more time getting the mock to work correctly rather than my app code. The lambada + generics based Mock suites (Moq, RhinoMocks, etc), IMO, complicate the test and make them unreadable in some situations.

 

Compare the two examples in this post. One uses RhinoMocks to create a stub of IDataReader and the other uses the DataTableReader to create a stub for the test. Which example is simpler and has less chance to fail due to the stub?

 

 http://www.lazycoder.com/weblog/2008/12/12/mocking-idatareader-using-rhinomocks-35/

Using RhinoMocks

IDataReader reader = MockRepository.GenerateStub<IDataReader>();
            reader.Stub(x => x.Read()).Return(true).Repeat.Times(1);
            reader.Stub(x => x.Read()).Return(false);
            reader.Stub(x => x["ID"]).Return(Guid.Empty);
            reader.Stub(x => x["FullName"]).Return("Test User");

Using DataTableReader

DataTable table = new DataTable();
            DataRow row = table.NewRow();
            table.Columns.Add(new DataColumn("ID"));
            table.Columns.Add(new DataColumn("FullName"));
            row["DirectoryUserID"] = Guid.Empty;
            row["FullName"] = "Test User";
            table.Rows.Add(row);
            DataTableReader reader = new DataTableReader(table);

Stubs/Fakes allow me more control over HOW the test fails and results in a test/fixture that is easier to read. I’m not saying that mocks aren’t useful in certain situations, but I would favor a stub over a mock IMO, your test should only fail because of the code it is testing, not because of a mock.

 

Although it is fun to say "Mock ME? No mock YOU!".

update: I forgot to link to Rob’s post that inspired this post. “Using Dependency Injection and Mocking For Testability

update to the update: Jeremy Miller and Nikola Malovic both pointed out that I’m using the terminology incorrectly. It turns out I don’t specifically hate mocks themselves, I dislike use dynamic mocking/stubbing frameworks due to the extra dependency they introduce into my tests. Thanks for the corrections. Back to reading Fowler for me!

JavaScript: Not for the faint at heart?

JavaScript: A tool too sharp?

Script# (Script Sharp) – writing javascript in C#

Both Jimmy and roy have great posts discussing JavaScript. Roy is looking at it as a C# developer lured by the many, many articles about how jQuery is the only thing that makes JavaScript worth using and using Script# to abstract away some of the messiness and pain usually associated with writing JavaScript. Jimmy discusses the merits of JavaScript itself and how it has changed how he approaches writing C# code.

One thing I like to point to is a great quote I heard on Twitter

Java is to JavaScript as ham is to hamster

hamster2.jpg

JavaScript actually has more in common with Scheme or Lisp than it does Java or C#. I first realized this when I saw that Douglas Crockford had re-written all of the examples in The Little Schemer
in JavaScript. It’s easy to miss that fact when you see all of the pseudo OOP noise like “var foo = new Foo();”. But when you see how trvial it is to implement something like a map method in JavaScript, you realize how powerful the language can be. Most of the hatred for JavaScript comes from two things I’ve found:

  1. Broken DOM implementations – every browsers implementation of the DOM is broken in one respect or another.
  2. A misunderstanding of either scope or inheritance.

Roy has a great point about the lack of good tooling surrounding JavaScript. There are excellent libraries like jQuery and PrototypeJS, but the usual tool support, intellisense, re-factoring, profiling, is a little more difficult to come by. I’ll address this in another post as I feel a lot of people are new to JavaScript and are struggling along with some substandard tools.

Declaration of Awesomeness for the Mono Compiler

MonoDevelop 2.0 Beta 1 – Miguel de Icaza

Now, technically speaking we have not received any awards for our C# 3.0 compiler, but we should have, because we are awesome. And in fact, I will be arranging a dinner at my place this coming weekend where we will award prizes to the best pieces of technologies and our C# compiler is a nominee.

We the undersigned do hereby declare the Mono C# 3.0 compiler to be awesome. This is not meant to denigrate the .NET compiler from Microsoft as it is a fine compiler in its own right. We are declaring the Mono C# 3.0 compiler to be an awesome piece of work by a ragtag group of merrymakers well-dressed group of distinguished gentlemen and worthy of all levels of awesomeness.

Leave a comment if you believe the Mono C# 3.0 compiler to be awesome.

Mocking IDataReader using Rhino.Mocks 3.5

The other day I was writing unit tests for some legacy code and I needed to mock IDataReader. I really just wanted to populate the reader with a single row of data, then the Read() method should return false. Using Rhino.Mocks it was a piece of cake.

            IDataReader reader = MockRepository.GenerateStub<IDataReader>();

            reader.Stub(x => x.Read()).Return(true).Repeat.Times(1);

            reader.Stub(x => x.Read()).Return(false);

            reader.Stub(x => x["ID"]).Return(Guid.Empty);

            reader.Stub(x => x["FullName"]).Return("Test User");

 

            List<UserDTO> list = SearchProvider.ParseUserData(reader);

            Assert.IsNotNull(list);

The magic happens in the Repeat.Times(1) statement. This tells Rhino.Mocks that when the method is called, the mock should Return the given value that number of times. After that it can return a different value.

Update: Jeremy Miller told me about the DataTableReader class in the BCL and that you can use it to stub out IDataReader. I like this better because it removes the dependency the test had on Rhino.Mocks.

            DataTable table = new DataTable();
            DataRow row = table.NewRow();
            table.Columns.Add(new DataColumn("ID"));
            table.Columns.Add(new DataColumn("FullName"));
            row["DirectoryUserID"] = Guid.Empty;
            row["FullName"] = "Test User";
            table.Rows.Add(row);
            DataTableReader reader = new DataTableReader(table);

Dynamic Lookup in C# 4

Charlie Calvert’s Community Blog : Future Focus I: Dynamic Lookup: “”

Charlie Calvert is discussing a new feature in C# called dynamic lookup

The next version of Visual Studio will provide a common infrastructure that will enable all .NET languages, including C#, to optionally resolve names in a program at runtime instead of compile time. We call this technology dynamic lookup.

Visual Basic already has this functionality in the form of late binding.

He also provides a short sample illustrating the change.

static void Main(string[] args)
{
    dynamic
    {
        object myDynamicObject = GetDynamicObject();
        myDynamicObject.SomeMethod();         // call a method   
        myDynamicObject.someString = "value"; // Set a field
        myDynamicObject[0] = 25;              // Access an indexer
    }
}

The dynamic keyword seems kind of bizarre to me. It looks like they are trying to shoehorn dynamic dispatch into .NET. Which is fine by me.
Probably the biggest language that uses dynamic dispatch in use today is Javascript. At runtime, all javascript methods are stored as members of the parent object. By using the objects prototype object, methods can be queried and added to the object. When a method is executed against an object in Javascript, first the members of the object itself are queried. If the method isn’t found, the objects prototype chain is checked for the method.

I’m not sure I like using special case keywords in C#, unsafe was the first one, instead of changing the language. To me, it feels like they are trying to make C# be all things to all people. My personal feelings are the statically typed languages are going the way of the manual transmission. But trying to cram dynamic features in a static languages is a bad idea. Just get the DLR out and make it a first class runtime environment in the .NET ecosystem. And make sure that managed Javascript, not JSCript ACTUAL ECMAScript, is in there. That way the bracket-lovers will still be happy, but they won’t be held back by having to write out a bunch of generic declarations and casting operations.

Adding values to the DataGridViewComboBoxCell at runtime

Welcome to hackville population me.

The DataGridViewComboBoxCell won’t allow values to be entered in the cell if they are not in the Items collection. Since I can’t modify the Items collection if the DataSource property is set, I add value of the cell that’s causing the DataError to the DataSource for the combo box. Since it doesn’t throw anything sensible like a ComboBoxValueNotInItems exception, and it doesn’t raise something nice like a “DataBinding” event or an “ValueNotInItems” event, or even an “Validating” event, I have to trap the System.ArgumentException. This may come back to bite me later. For one thing, will I ALWAYS set the Datasource to a DataTable object? What if I use another object for the data source.

        private void dgStuff_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
 
            if (e.Exception is System.ArgumentException)
            {
                if (this.dgStuff.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewComboBoxCell)
                {
                    DataGridViewComboBoxCell _cell = this.dgStuffDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewComboBoxCell;
                    DataTable _dt = _cell.DataSource as DataTable;
                    DataRow _newRow = _dt.NewRow();
                    _newRow["LkpCode"] = _cell.Value;
                    _newRow["LkpDescription"] = _cell.Value;
                    _dt.Rows.Add(_newRow);
                    _dt.AcceptChanges();
                }
            }
        }

I found a post in the MSDN forums where they talk about accepting user input in the DataGridViewComboBoxCell which isn’t in the cells Items collection.