Revealed on: November 28, 2024
In a earlier submit, I wrote about utilizing the #count on
macro to make sure that sure assertions you need to make about your code are true. We checked out testing boolean circumstances in addition to errors.
On this submit, I would love to try a macro that goes hand-in-hand with #count on
and that’s the #require
macro.
The #require
macro is used to make sure that sure circumstances in your take a look at are met, and to abort your take a look at if these circumstances aren’t met. The important thing distinction between #count on
and #require
is that #count on
is not going to trigger a failed assertion to cease the take a look at.
#require
is way stricter. If we discover one assertion to be unfaithful inside the #require
macro, we finish the take a look at as a result of we do not assume it is sensible to check any additional.
On this submit, we’ll check out a number of functions of the #require
macro. For instance, we’ll use #require
to make sure that an optionally available worth may be unwrapped. We’ll additionally see how you should use #require
to make sure that a particular error is or is just not thrown. And naturally, we’ll additionally take a look at boolean circumstances inside #require
.
Let’s begin by taking a look at Optionally available
.
Unwrapping optionals with #require
Typically in our code we may have optionally available values. They’re just about unavoidable in Swift they usually’re truly a extremely great tool. In your take a look at, it’s fairly probably that you’re going to need to ensure that a sure worth exists earlier than continuing together with your take a look at. A method to do that can be to make use of the #count on
macro and be certain that some property or worth is just not nil
.
Nonetheless, generally you may need to take your optionally available worth and use it as enter for one thing else otherwise you need to do additional testing with that object. In that case, it is sensible to abort your take a look at totally if the optionally available occurs to be nil
.
We are able to use the #require
macro for this, right here’s how:
@Take a look at func userIsReturned() async throws {
let userStore = UserInfoStore()
let consumer = Consumer(title: "John")
userStore.addUser(consumer: consumer)
let returnedUser = attempt #require(userStore.getUser(withName: "John"), "Consumer retailer ought to return the consumer that was added")
#count on(returnedUser == consumer, "Consumer retailer ought to return the consumer that was added")
}
The magic right here is on the road the place we create our let returnedUser
. We use the #require
macro and we name it with the attempt
key phrase.
That is as a result of if the #require
macro fails to unwrap the optionally available that’s returned by getUser
, the macro will throw an error and so our take a look at will truly fail. That is fairly helpful if you actually do not need to proceed your take a look at if no matter you are attempting to require is not there.
So on this case I need to examine the return consumer with the one which I’ve tried to retailer. I can’t try this if the consumer is not there. So I need my take a look at to not simply fail when the optionally available that is returned by getUser
is nil
, I need this take a look at case to finish.
Now let’s think about that I additionally need to finish my take a look at if the returned consumer and the saved consumer aren’t the identical…
Checking boolean circumstances with #require
Within the earlier part I used the next to line to ensure that my getUser
perform returned the right consumer:
#count on(returnedUser == consumer, "Consumer retailer ought to return the consumer that was added")
Discover how I am utilizing #count on
to check my returned consumer to my saved consumer.
This expectation will enable my take a look at to proceed operating even when the expectation fails. This could enable me to carry out a number of assertions on an object. For instance, if I have been to examine whether or not the consumer title, the consumer’s ID, and a bunch of different properties match, I might use #count on
in order that I can carry out all assertions and see precisely which of them failed.
On this case I might need my take a look at to fail and finish if I didn’t get the proper consumer again.
So I am evaluating the 2 customers like earlier than and I’ve changed my #count on
with #require
. Here is what that appears like in a full take a look at.
@Take a look at func userIsReturned() async throws {
let userStore = UserInfoStore()
let consumer = Consumer(title: "John")
userStore.addUser(consumer: consumer)
let returnedUser = attempt #require(userStore.getUser(withName: "John"), "Consumer retailer ought to return the consumer that was added")
attempt #require(returnedUser == consumer, "Consumer retailer ought to return the consumer that was added")
print("this may not run if I received the incorrect consumer")
}
Discover that I needed to prefix my #require
with the attempt
key phrase, identical to I had for getting my returned consumer on the road earlier than.
The rationale for that’s if I did not get the proper consumer again and it would not match with the consumer that I simply saved, my take a look at will throw an error and finish with a failure.
Total, the APIs for #require
and #count on
are fairly related, with the important thing distinction being that #require
wants the attempt
key phrase and your take a look at ends if a requirement is not met.
Now that we have seen how we will use this to unwrap optionals and examine boolean circumstances, the following step is to see how we will use it to examine for sure errors being thrown.
Checking errors with #require
If you know the way to examine for errors with the #count on
macro, you principally know tips on how to it do with the #require
macro too.
The important thing distinction being as soon as once more if a requirement is just not met your take a look at case will cease.
If you wish to be taught extra about checking for errors, I urge you to try my weblog submit on the #count on
macro. I do not need to duplicate all the pieces that is in there on this submit, so for an in-depth overview, you possibly can check out that submit.
On this submit, I might identical to to provide you a quick rundown of what it seems prefer to examine for errors with the #require
macro.
So first let’s examine how we will assert that sure perform throws an anticipated error with the #require
macro.
I will likely be utilizing the identical instance that I used within the earlier submit. We’ll examine that giving an incorrect enter to an object will truly throw the error that I need to obtain.
@Take a look at func errorIsThrownForIncorrectInput() async throws {
let enter = -1
attempt #require(throws: ValidationError.valueTooSmall(margin: 1), "Values between 0 and 100 needs to be okay") {
attempt checkInput(enter)
}
}
On this particular instance, it won’t make a ton of sense to make use of #require
over #count on
. Nonetheless, if I have been to have extra code after this assertion and it would not make sense to proceed my take a look at if the incorrect error was thrown, then it makes complete sense for me to make use of #require
as a result of I need to abandon the take a look at as a result of there is no level in persevering with on.
Much like the #count on
macro, we will cross a particular error (like I did within the instance above) or an error sort (like ValidationError.self
). If we need to assert that no error is thrown, we might cross By no means.self
because the error. sort to ensure that our perform name doesn’t throw.
Much like the #count on
macro, you should use the #require
macro to examine whether or not a sure expression throws an error based mostly on a extra sophisticated analysis.
For all of the totally different overloads that exist on #require
, I want to redirect you to the #count on
macro submit as a result of they’re precisely the identical for #require
and #count on
. The important thing distinction is what occurs when the assertion fails: #count on
will enable your take a look at to proceed, however it’s going to fail with an error on the road the place your assertion failed. With #require
, your take a look at case will merely finish on the road the place one thing that you simply did not count on truly occurred.
In Abstract
Total, I fairly like that Swift testing permits us to have a free checking for assertions within the #count on
macro, the place we will validate that sure issues are or aren’t appropriate with out failing the whole take a look at. That may mean you can make a complete bunch of assertions and see which of them fail, fixing one drawback at a time (operating your take a look at once more, fixing the following drawback that exhibits up) is tedious.
The #require
macro is very nice if you just about depend on one thing to be returned or one thing to be true earlier than you possibly can proceed.
For instance, unwrapping an optionally available if you wish to use no matter you are attempting to unwrap to run additional code and carry out additional assertions. It is mindless to proceed your take a look at as a result of you understand that each single assertion that comes after it’s going to fail, so I actually like utilizing #require
for these sorts of conditions and #count on
for those the place I can proceed my take a look at to gather extra details about the outcomes.