Add Custom Messages in Assert

Add custom messages in assert?

A hack I've seen around is to use the && operator. Since a pointer "is true" if it's non-null, you can do the following without altering the condition:

assert(a == b && "A is not equal to B");

Since assert shows the condition that failed, it will display your message too. If it's not enough, you can write your own myAssert function or macro that will display whatever you want.

Adding message to assert

You are out of luck here. The best way is to define your own assert macro.

Basically, it can look like this:

#ifndef NDEBUG
# define ASSERT(condition, message) \
do { \
if (! (condition)) { \
std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
<< " line " << __LINE__ << ": " << message << std::endl; \
std::terminate(); \
} \
} while (false)
#else
# define ASSERT(condition, message) do { } while (false)
#endif

This will define the ASSERT macro only if the no-debug macro NDEBUG isn’t defined.

Then you’d use it like this:

ASSERT((0 < x) && (x < 10), "x was " << x);

Which is a bit simpler than your usage since you don’t need to stringify "x was " and x explicitly, this is done implicitly by the macro.

Julia: add custom message in assert?

From the documentation:

@assert false "Expected true"

@assert cond [text]

Throw an AssertionError if cond is false. Preferred syntax for writing assertions. Message text is optionally displayed upon assertion failure.

How to Add message to the @Assert?

Solved thanks to msg comment!

In case anyone faced this error u can use novalidate attribute to disable browser validation!

instead of

{{ form_start(form) }}

use

{{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}

Set Custom Error Message for Assert (Node.js)

You cannot, without tampering with the 3rd party lib assert

Behind the scenes, uses a fail function, that is private in the context of assert and you cannot tell assert to use a custom fail function.

this is the function used behind the scenes:

function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}

As such, you have three options:

  1. (recommended) Fork the lib on github. Implement either some watchers like onFail or allow it to be extensible and create a pull request.

  2. (not recommended) Overwrite the fail function in the node_modules\assert\assert.js file yourself so that, besides triggering the usual stuff, it does what you want as well.

    While quick, this will cause a broken dependency forever.

  3. Look for other assertions libraries (if there are any that fit your needs)

Can you add a custom message to AssertJ assertThat?

And in classic fashion, I found what I was looking for moments after posting the question. Hopefully this will make it easier for the next person to find without first having to know what it's called. The magic method is the deceptively short-named as, which is part of another interface that AbstractAssert implements: Descriptable, not the base Assert interface.

public S as(String description, Object... args)

Sets the description of this object supporting String.format(String, Object...) syntax.

Example :

try {
// set a bad age to Mr Frodo which is really 33 years old.
frodo.setAge(50);
// you can specify a test description with as() method or describedAs(), it supports String format args
assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33);
} catch (AssertionError e) {
assertThat(e).hasMessage("[check Frodo's age] expected:<[33]> but was:<[50]>");
}

Where that quoted string in the catch block hasMessage is what appears in your unit test output log if the assertion fails.


I found this by noticing the failWithMessage helper in the custom assert page linked in the question. The JavaDoc for that method points out that it is protected, so it can't be used by callers to set a custom message. It does however mention the as helper:

Moreover, this method honors any description set with as(String, Object...) or overridden error message defined by the user with overridingErrorMessage(String, Object...).

... and the overridingErrorMessage helper, which completely replaces the standard AssertJ expected: ... but was:... message with the new string provided.

The AssertJ homepage doesn't mention either helper until the features highlights page, which shows examples of the as helper in the Soft Assertions section, but doesn't directly describe what it does.

How to write a custom assert function that accepts assert messages like this: assert(false) assertion failed;

Minimal correction:

const AssertHelper& operator<<(const std::string& mesg) const
{
if (!assert_state)
std::cerr << mesg;
return *this;
};

~AssertHelper()
{
if (!assert_state)
{
std::cerr << std::endl;
exit(-1);
}
}

Remarks: operator<< should return a reference, not a value; bool assert_state; can be marked as const; calling flush() after << std::endl is superfluous.

Is there any opportunity to add an assertion message in Rest Assured method?

No, Rest-Assured doesn't have any methods like this.

To add assertion message, you can use Hamcrest directly.

Response res = given().when().get("your_url");
assertThat("Check status code", res.statusCode(), Matchers.is(200));

How to create custom FluentAssertion error messages?

using (new AssertionScope())
{
foreach (var parameterType in parameterTypes)
{
var fooType = typeof(IFoo<>);
var genericType = providerType.MakeGenericType(parameterType);

using _ = new AssertionScope(fooType.GetPrettyName());

serviceProvider
.GetService(fooType)
.Should()
.NotBeNull($"all Foo types should be registered");
}
}


Related Topics



Leave a reply



Submit