Reputation: 891
I have a getter only property like
public ICar Car
{
{
get
{
return _car ?? (_car = GetCar());
}
}
}
GetCar()
will throw NotSupportedException
under certain circumstances and I want to unit test this. I am using Moq.
I am trying to use this in my unit test but it does not work on properties, only on methods
var sut = new CarProcessor(...); //init subject under test
Assert.Throws<NotSupportedException>(() => sut.Car); //evaluate result of Car property
This wont compile and it says "Only assignment call, increment, decrement, await and new object expression can be used as a statement" error.
Doing same as above for a method instead property works fine.
Upvotes: 0
Views: 318
Reputation: 9714
You can work around this by assigning the property in a statement lambda, like so:
Assert.Throws<NotSupportedException>(() => { var _ = sut.Car; });
This will attempt to assign the property to a throwaway variable _
(C# 7+ only, use x
if you're compiling against a a lower language level), which should compile just fine.
Upvotes: 3