While a lot of people have talked about the ideas involved, nobody seems to have directly addressed the title question: how do you test for it the highest resolution.
In theory, the answer to that is pretty simple: you shoot at each aperture, and find which gave the highest quality.
In reality, it's rarely quite the easy. Let's start with the simplest case: a completely flat object that's exactly parallel to the film/sensor plane. In this case, you don't have to pay any attention to depth of field, but you still often get a bit of a choice. With many lenses, the center will be at its sharpest at one aperture, but the corners will be the sharpest at another (usually slightly smaller) aperture. For (a reasonably typical) example, the center might be the sharpest at f/5.6, but the corners at around f/8 to f/9.5 or so.
When we add in a third dimension, things get more interesting still. A smaller aperture increases depth of field. In a real picture, you'll often get a greater portion that's reasonably sharp by using an even smaller aperture than either of those noted above. For example, here's a sequence at f/4.5, f/8 and f/11:
f/4.5:
f/8:
f/11:

Quite a bit more than just sharpness and depth of field change change with aperture though. Just for example, even if you look at only one part of a picture, chromatic aberration might be minimized at one aperture, contrast maximized at a second aperture, and spherical aberration minimized at a third.
You also need to separate quality from which picture works best. In the series above, the f/8 version is (minutely) sharper at the corners (though I can't see the difference at the size above), but I definitely prefer the f/4.5 version because the background is less distracting.
I should probably mention one other wrinkle: you can (and some people do) use what's called focus stacking to increase (apparent) depth of field, while retaining higher sharpness than you'd (usually) get from just stopping down to a really small aperture. The basic idea is pretty simple: you take a number of pictures focused at different distances, and then create a composite built from the sharp parts of each of those shots. For example:
Near focus:

Far focus:

Composite:

Note that the composite isn't really just from these 2 shots, but from a total of 5, so this can be a fair amount of work. If you look closely at the composite, you can see that I really should have used even more shots with the focus points a bit closer together. For example, the near flower and far flower are both reasonably sharp, but some of the leaves in between really aren't.