Printed on: November 28, 2024
In a earlier submit, I wrote about utilizing the #count on
macro to make sure that sure assertions you wish 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 should not met. The important thing distinction between #count on
and #require
is that #count on
won’t trigger a failed assertion to cease the take a look at.
#require
is far 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 suppose it is smart 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 elective worth could be unwrapped. We’ll additionally see how you should utilize #require
to make sure that a selected error is or will not be thrown. And naturally, we’ll additionally take a look at boolean circumstances inside #require
.
Let’s begin by taking a look at Non-compulsory
.
Unwrapping optionals with #require
Generally in our code we may have elective values. They’re just about unavoidable in Swift they usually’re really a extremely useful gizmo. In your take a look at, it’s fairly seemingly that you’re going to wish to make it possible for a sure worth exists earlier than continuing along with your take a look at. A method to do that can be to make use of the #count on
macro and make sure that some property or worth will not be nil
.
Nevertheless, generally you may wish to take your elective worth and use it as enter for one thing else otherwise you wish to do additional testing with that object. In that case, it is smart to abort your take a look at completely if the elective occurs to be nil
.
We will use the #require
macro for this, right here’s how:
@Check func userIsReturned() async throws {
let userStore = UserInfoStore()
let consumer = Person(title: "John")
userStore.addUser(consumer: consumer)
let returnedUser = strive #require(userStore.getUser(withName: "John"), "Person retailer ought to return the consumer that was added")
#count on(returnedUser == consumer, "Person 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 strive
key phrase.
That is as a result of if the #require
macro fails to unwrap the elective that’s returned by getUser
, the macro will throw an error and so our take a look at will really fail. That is fairly helpful while you actually do not wish to proceed your take a look at if no matter you are making an attempt to require is not there.
So on this case I wish to examine the return consumer with the one which I’ve tried to retailer. I can not do this if the consumer is not there. So I need my take a look at to not simply fail when the elective 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 wish 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 make it possible for my getUser
operate returned the proper consumer:
#count on(returnedUser == consumer, "Person retailer ought to return the consumer that was added")
Discover how I am utilizing #count on
to match my returned consumer to my saved consumer.
This expectation will permit my take a look at to proceed operating even when the expectation fails. This may permit me to carry out a number of assertions on an object. For instance, if I had 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 fitting 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.
@Check func userIsReturned() async throws {
let userStore = UserInfoStore()
let consumer = Person(title: "John")
userStore.addUser(consumer: consumer)
let returnedUser = strive #require(userStore.getUser(withName: "John"), "Person retailer ought to return the consumer that was added")
strive #require(returnedUser == consumer, "Person retailer ought to return the consumer that was added")
print("this may not run if I acquired the incorrect consumer")
}
Discover that I needed to prefix my #require
with the strive
key phrase, similar to I had for getting my returned consumer on the road earlier than.
The rationale for that’s if I did not get the fitting 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.
General, the APIs for #require
and #count on
are fairly comparable, with the important thing distinction being that #require
wants the strive
key phrase and your take a look at ends if a requirement is not met.
Now that we have seen how we are able to use this to unwrap optionals and examine boolean circumstances, the subsequent step is to see how we are able to use it to examine for sure errors being thrown.
Checking errors with #require
If you understand how to examine for errors with the #count on
macro, you mainly know it do with the #require
macro too.
The important thing distinction being as soon as once more if a requirement will not be 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 wish to duplicate all the things 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 similar to to provide you a short rundown of what it appears to be like prefer to examine for errors with the #require
macro.
So first let’s examine how we are able to assert that sure operate throws an anticipated error with the #require
macro.
I can be utilizing the identical instance that I used within the earlier submit. We will examine that giving an incorrect enter to an object will really throw the error that I wish to obtain.
@Check func errorIsThrownForIncorrectInput() async throws {
let enter = -1
strive #require(throws: ValidationError.valueTooSmall(margin: 1), "Values between 0 and 100 must be okay") {
strive checkInput(enter)
}
}
On this particular instance, it may not make a ton of sense to make use of #require
over #count on
. Nevertheless, if I had 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 whole sense for me to make use of #require
as a result of I wish to abandon the take a look at as a result of there is no level in persevering with on.
Just like the #count on
macro, we are able to move a selected error (like I did within the instance above) or an error kind (like ValidationError.self
). If we wish to assert that no error is thrown, we may move By no means.self
because the error. kind to make it possible for our operate name doesn’t throw.
Just like the #count on
macro, you should utilize the #require
macro to examine whether or not a sure expression throws an error primarily based on a extra sophisticated analysis.
For all of the completely different overloads that exist on #require
, I wish 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 permit your take a look at to proceed, however it can 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 just did not count on really occurred.
In Abstract
General, I fairly like that Swift testing permits us to have a unfastened checking for assertions within the #count on
macro, the place we are able to validate that sure issues are or should not appropriate with out failing your entire take a look at. That might assist you to make a complete bunch of assertions and see which of them fail, fixing one downside at a time (operating your take a look at once more, fixing the subsequent downside that reveals up) is tedious.
The #require
macro is very nice while 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 elective if you wish to use no matter you are making an attempt to unwrap to run additional code and carry out additional assertions. It is not sensible to proceed your take a look at as a result of you already know that each single assertion that comes after it can 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.