How do I get Apple Hardware Test working on a refurbished Mac?

For this model, Apple Hardware Test actually comes pre-installed on the hard drive.

If you've reformatted or replaced the original hard drive, it's possible to install Apple Hardware Test back to it from a downloadable disk image, but you need to boot the system using the Recovery partition on another disk to do it:

  1. Download the appropriate Apple Hardware Test disk image for your machine (partial list at https://github.com/upekkha/AppleHardwareTest)

  2. Reboot into recovery mode, by holding the option key down at boot, and then choosing the recovery partition from the menu

  3. Open Disk Utility, mount the Apple Hardware Test disk image, and then quit disk utility (with the disk image still mounted)

  4. Open Terminal from the Utilities menu

  5. Copy the System/Library/CoreServices/.diagnostics folder from the disk image to the new drive:

     cp -R /Volumes/AHTBTwo/System/Library/CoreServices/.diagnostics \
     /Volumes/Macintosh\ HD/System/Library/CoreServices/
    
  6. This copy of Apple Hardware Test is now installed; you should now be able to launch it by restarting while holding down d.

Background: The drive supplied with the machine had a recovery partition on it, but I don't know if that had the appropriate version of Apple Hardware Test for this machine. In any case, I also neglected to copy the recovery partition across to the new drive when I copied the Macintosh HD volume. I had done that using a Mac OS X Install Disk's copy of Disk Utility with the new drive on a USB adapter before I installed it in the MacBook.

To get a recovery partition back, following the nice guide at https://www.lifewire.com/create-os-x-recovery-hd-on-any-drive-2260909 I manually took a disk image of the recovery partition on the old drive using a Terminal command:

sudo hdiutil create ~/Desktop/Recovery\ HD.dmg -srcdevice /dev/disk2s3 

and then ran Disk Utility and made a partition for it on the new disk, and restored that partition from the Recovery HD.dmg disk image.

That gives the new recovery partition on the new disk the right contents to be a recovery partition, but it still has the default partition type code that Disk Utility sets, which is for a regular Mac OS X partition.

To change the partition type value for the recovery partition, which is normally prevented by the integrity protection in Sierra, I rebooted from the recovery partition on the old disk, and then ran the commands in a Terminal there:

diskutil unmount /dev/diskXXX
sudo asr adjust --target /dev/diskXXX -settype Apple_Boot

(Use whatever Device shows up in Disk Utility for the new recovery partition in place of diskXXX)

At that point I had a usable recovery partition on the new disk, and I could follow the steps up above to add Apple Hardware Test.