I have been reworking some classes to make them more testable. I need to be able to test the constructor to make sure that it throws an exception when I have images that are different sizes. The problem is that I am no longer creating this class using a List<Bitmap> because I need to know the file name for the image.
My question is how can I mock the property that is used to get the image list before creating an instance of the class to determine if it throws an exception?
Update:
At this point I have been able to get a valid test working using the following code and xUnit:
The problem I have at the moment is that when I change:
To
The unit test will fail because it is not retuning the list of images that I created using Mock.Arrange(). Can someone please let me know what I need to do differently to get this to work?
My question is how can I mock the property that is used to get the image list before creating an instance of the class to determine if it throws an exception?
Update:
At this point I have been able to get a valid test working using the following code and xUnit:
public
class
MockTest
{
[Fact]
public
void
ShouldThrowExceptionWhenImagesAreDifferentSizes()
{
Foo foo =
null
;
Mock.Arrange(() => foo.GetImageList()).Returns(
new
List<Bitmap> {
new
Bitmap(100, 100),
new
Bitmap(200, 200) });
Assert.Throws<ApplicationException>(() => foo =
new
Foo(
null
));
}
public
class
Foo
{
public
Foo(List<FileInfo> files)
{
this
.CheckImageDimensions();
}
public
void
CheckImageDimensions()
{
Bitmap firstImage =
this
.Images.FirstOrDefault();
Bitmap invalidImage =
this
.Images.Where(x => x.Width != firstImage.Width || x.Height != firstImage.Height).FirstOrDefault();
if
(invalidImage !=
null
)
throw
new
ApplicationException(
"Images with different dimensions are not supported."
);
}
private
List<Bitmap> _imageList;
public
List<Bitmap> Images
{
get
{
if
(
this
._imageList !=
null
)
return
this
._imageList;
this
._imageList =
this
.GetImageList();
return
this
._imageList;
}
}
public
List<Bitmap> GetImageList()
{
throw
new
NotImplementedException();
}
}
}
The problem I have at the moment is that when I change:
Mock.Arrange(() => foo.GetImageList()).Returns(
new
List<Bitmap> {
new
Bitmap(100, 100),
new
Bitmap(200, 200) });
To
Mock.Arrange(() => foo.Images).Returns(
new
List<Bitmap> {
new
Bitmap(100, 100),
new
Bitmap(200, 200) });
The unit test will fail because it is not retuning the list of images that I created using Mock.Arrange(). Can someone please let me know what I need to do differently to get this to work?