I've seen few sample sitecore applications which uses the code below within the business logics:
Database database = Factory.GetDatabase(itemUri.DatabaseName);
Assert.IsNotNull(database, itemUri.DatabaseName);
return database.GetItem(attribute);
Could someone please clarify if this is a sitecore convention. I've only used Assert for unit testing scenarios but not within logic.
Thanks.
I found this article which addresses most of your question. There are a couple of important points:
I think it is also important to note that many of the examples I seem to be finding in the Sitecore blogs are cases where an exception would happen anyway. So, if ArgumentIsNotNull
were to be omitted, for example, that would result in a NullObjectException
, so an Assert actually cleans things up a bit. In your case, if the Database is unavailable, that would also cause a problem. An Assert makes it so that cause of the error is clear.
It is a convention that can be seen heviliy used in the sitecore.dll's. It is used to throw an exception if that condition is not met.
For example if you look at Assert.IsTrue, if the condition is not met the system will throw a "InvalidOperationException"
De-compiling the a method from the Search API I found this.
Assert.IsTrue(local_0 != null, "SearchConfiguration is missing");
Then if we de-compile IsTrue, it gives us
[AssertionMethod]
public static void IsTrue([AssertionCondition(AssertionConditionType.IS_TRUE)] bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
To Answer your other question you can use this in your application code, as you can see its just another way of throwing an exception if a condition is not met.
The confusion comes with the use of the word assert, which as you said is usually seen in context of unit tests in a traditional c# .NET solution. As long as you know what the Sitecore assert is doing behind the scenes, its up to you if you want to use it or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With