[Moq] Set Property returns null in a setup method.

1,324 views
Skip to first unread message

cankayacan

unread,
Apr 28, 2010, 7:35:18 AM4/28/10
to Moq Discussions
Hello,

In my Silverlight application, I have a ProductViewModel that holds a
SelectedItem (type of Product). The Component property inside the
Product normally throws an error when a null value is assigned to it.
I want to validate whether this scenario works correctly via Moq.

Here is the test method:

/// <summary>
/// Test method to validate a product with an empty component
is invalid.
/// </summary>
[Test]
public void TestValidateComponentRequired()
{
var productModel = new Product();
var productViewModel = new Mock<ProductViewModel>();

productViewModel.SetupProperty<Product>(p =>
p.SelectedItem, productModel); // SelectedItem will return
productModel

Product productModel2 =
productViewModel.Object.SelectedItem; // SelectedItem returns
productModel successfully

// HERE, p.SelectedItem returns null and I cannot setup
Component to throw an exception when it is assigned null
productViewModel.SetupSet(p => p.SelectedItem.Component =
null).Throws<Exception>().Verifiable();

try { productViewModel.Object.SelectedItem.Component =
null; }
catch { }

productViewModel.Verify();
}

--
Post: moq...@googlegroups.com
Unsubscribe: moqdisc-u...@googlegroups.com

Emanuele DelBono

unread,
Apr 29, 2010, 3:29:34 AM4/29/10
to moq...@googlegroups.com
I don't understand what you're trying to do in your test, but, if you
want to test that when you set product.Component to null product will
trhow an exception you don't even need a mock:

[Test]
[ExpecetedException(typeof(invalidOperationException))
public void SetComponentToNullThrowsAnException()
{
Product p = new Product()
p.Component = null;
}

Instead if you want to verify the interaction between ViewModel and
Product, you shouldn't mock the viewmodel but the product, something
like this:

[Test]
public void TestValidateComponentRequired()
{
var product = new Mock<Product>();
var productViewModel = new ProductViewModel();

product.SetupSet(p => p.SelectedItem.Component =
null).Throws<Exception>();

try {
productViewModel.Object.SelectedItem.Component = null; }
catch { }
}


ema
http://blog.codiceplastico.com
Reply all
Reply to author
Forward
0 new messages