I stumbled upon a weird exception problem while working on test methods. Basically, i throw an exception inside an if statement which isn't catched by the try-catch above it. All seems to be related to the GalaSoft.MvvmLight.Command.RelayCommand and a line after the exception is thrown. Here are some code snippets if you guys want to reproduce the problem : Here is my test method
[TestMethod]
public void TestRelayCommand()
{
TestEditVM t = new TestEditVM();
bool argumentNullExceptionCatched = false;
try
{
t.lists.Add(new MyObject());
t.MyCommand.Execute(null);
//t.MethodToTest();
}
catch (ArgumentNullException)
{
argumentNullExceptionCatched = true;
}
Assert.IsTrue(argumentNullExceptionCatched);
}
and here is my TestEditVM along with a small class used by it
class TestEditVM
{
public ObservableCollection<MyObject> lists = new ObservableCollection<MyObject>();
public void MethodToTest()
{
int i = 0;
int j = 1;
int k = 1;
i++;
//throw new ArgumentNullException();
if (j == k)
throw new ArgumentNullException("lorem", "ipsum");
i++;
//throw new ArgumentNullException();
var lvm = (lists.FirstOrDefault(l => l.IsQueryOwner(null)));
}
private RelayCommand _myCommand;
public RelayCommand MyCommand
{
get
{
if (_myCommand == null)
{
_myCommand = new RelayCommand(() =>
{
int i = 0;
int j = 1;
int k = 1;
i++;
//throw new ArgumentNullException();
if (j == k)
throw new ArgumentNullException("lorem", "ipsum");
i++;
//throw new ArgumentNullException();
var lvm = (lists.FirstOrDefault(l => l.IsQueryOwner(null)));
}
);
}
return _myCommand;
}
}
}
class MyObject
{
public int Id { get; set; }
public MyObject Query { get; set; }
public bool IsQueryOwner(MyObject query)
{
if (query == null)
throw new Exception("MyObject exception");
return Query.Id == query.Id;
}
}
If i comment out the LinQ line, the exception is thrown and catched as expected. The same code running Inside TestMethod1() always behaves normally.
Also, i noticed that if one of the "throw" statements are uncommented, the code behaves as expected and the exception is catched. I believe this is some work done by the compiler to not include unreachable code during the execution (i.e. the bogus linq line)
I am running this test project on VisualStudio 2013, on .net Framework 4.5 with the latest mvvm light Framework available on NuGet.
Any help or explanation would be greatly appreciated! Thanks!