I have a chain of property and indexer calls that includes a cast. I get an InvalidCastException on the cast, even though the code that I'm trying to test actually works.
It happened when I started using a BindingListView library to bind a List<> of Project objects to a DataGridView. Here's the code in my Presenter class that does the binding:
public void LoadData()
{
List<Project> projectsList = _scope.Extent<Project>().ToList();
_view.GridDataSource = new BindingListView<Project>( projectsList );
}
Then I use the following code to see which Project the user has selected in the grid:
public void SelectionChanged()
{
if ( _view.GridSelectedRows.Count == 1 )
{
SelectedProject =
( ( Equin.ApplicationFramework.ObjectView<Project> )
(_view.GridSelectedRows[0].DataBoundItem )).Object;
_view.EditButtonEnabled = true;
_view.DeleteButtonEnabled = true;
}
}
This code works when I run it. But I have problems when I try to test the code that loads SelectedProject using the following test:
/// <summary>
/// If the SelectionChanged() method is called when a Project is selected on the
/// form's ProjectsGrid, check that the SelectedProject is set to that Project
/// </summary>
[Test]
public void SelectionChangedToProject_SetsSelectedProject()
{
InstantiateProjects(); // Creates List<Project> _project
Isolate.WhenCalled( () => _viewFake.GridSelectedRows.Count ).
WillReturn( 1 );
Isolate.WhenCalled( () =>
( ( Equin.ApplicationFramework.ObjectView<Project> )
( _viewFake.GridSelectedRows[0].DataBoundItem ) ).Object ).
WillReturn( _projects[2] );
_presenter.SelectionChanged();
Isolate.Verify.WasCalledWithAnyArguments( () =>
( ( Equin.ApplicationFramework.ObjectView<Project> )
( _viewFake.GridSelectedRows[0].DataBoundItem ) ).Object );
Assert.AreSame( _projects[2], _presenter.SelectedProject );
}
It fails at Isolate.Verify with the message 'Unable to cast object of type 'System.Object' to type 'Equin.ApplicationFramework.ObjectView`1[Integrator.Management.Project]'.
I thought it may be due to the chain of properties and indexes. So I tried faking each part of the chain, but it always fails when it gets to the cast.