Hold the new medicine cabinet against the wall, exactly where you wish to mount the cabinet. Have another person use a pencil to trace around the medicine cabinet where it meets the wall.
Cut a small hole in the middle of the tracing you made on the wall, using a drywall knife. Angle the knife’s blade to the side as much as possible while you cut to avoid damage to any electrical wires or plumbing inside the wall. Look inside the wall with a flashlight for the presence of obstacles such as wiring or pipes that would prevent you from installing the medicine cabinet where you traced.
Cut the wall along the lines you traced, using the drywall knife. If you run into a wall stud, trim it along the line you traced, using a handsaw, and remove the portion of the stud inside the cutout.
Measure the dimensions of the cutout you made in the wall. Trim 2-by-4s with a circular saw, cutting lengths that fit inside the cutout, just under the edge of the wall.
Apply construction adhesive to the sides and ends of the boards you cut. Insert the boards under the edges of the wall cutout, holding them in place until the construction adhesive cures enough to keep the boards in place.
Drive screws through the wall and into the 2-by-4s, further anchoring the boards in place. Slide the medicine cabinet into the wall cavity. Drive screws through the mounting holes on the inside of the medicine cabinet, anchoring the screws into the boards you anchored in the wall.