throw icon indicating copy to clipboard operation
throw copied to clipboard

Have you considered building an assertion library?

Open slang25 opened this issue 2 years ago • 2 comments

Hey, I'm really impressed with the design this library, it's very well thought out.

Have you considered if some of this could be repurposed or made available in a way that would be usable as an assertion library?

I mean it could today, but it would be more idiomatic to throw a specific type of assertion exception, perhaps with a .Assert()... extension that does the Validatable<TValue> capture.

slang25 avatar Jun 14 '22 13:06 slang25

You can get halfway there by creating your own extension method:

public static Validatable<TValue> Assert<TValue>(this TValue value)
{
  return value.Throw<SpecificException>();
}

The problem is that it doesn't allow you to add an actual message or parameter name to the exception that is created. The closest you can get to that (with the current version of the library) is to add a constructor method that accepts the parameter name as an argument, but any of the lovely custom messages provided by the library are lost:

public static Validatable<TValue> Assert<TValue(this TValue value)
{
  return value.Throw(paramName => new SpecificException($"There was a problem with {paramName}.");
}

I have raised an issue separately that, amongst other things, suggests two new features that would solve your use case:

public static Validatable<TValue> Assert<TValue(this TValue value)
{
  // library is modified to automatically use the SpecificException's (string message) constructor to provide more information
  return value.Throw<SpecificException>();
}

// OR

public static Validatable<TValue> Assert<TValue(this TValue value)
{
//   need a new option added to ExceptionCustomizations to produce this result
  return value.Throw((paramName, message) => new SpecificException($"{message} (Parameter '{paramName}').");
}

truegoodwill avatar Jun 15 '22 07:06 truegoodwill

Thanks, @slang25, I think it's well thought out as well 😅 Are you familiar with FluentAssertions?

amantinband avatar Sep 04 '22 13:09 amantinband