I suggest you have a look at JTAG. It's widely known as a "programming protocol", but it can do much more. For example, it can daisy chain all I/O pins of multiple devices on a PCB, and then you can shift test vectors though these flipflops to test extra circuitry (for example simple logic gates, address decoders, TTL glue logic, etc) that is in between the bigger IC's that support JTAG (for example uC, FPGA, advanced ADC).
For the rest, it seems quite logical to program a uC in the factory with a test program (For example during "bed of nails" production testing), and then reprogram the uC with the final application afterwards. But as long as there is enough Flash in the uC, it usually makes more sense to simply add the test code to the application, combined with some way (Uart, SPI, I2C, I2S, whatever is available) to communicate with the uC during testing.
Normally electronics is tested quite thoroughly during manufacturing, and in various ways (For example AOI, temperature cycling, burn in test). If a big part of the testing can be done by an on board uC, then a (networked) assembly can be made as an integral part of the testing. For example, a room with a few thousand phones, all connected to an USB "distribution network" (Regular USB only supports a few levels deep nesting). that collect test data during thermal or burn in tests.
Industrial electronics is probably tested more thoroughly then consumer electronics, but even consumers will be pissed if even a single sensor on their new phone is defective, and this can harm a companies reputation too. So everything is tested, from copper tracks on the bare PCB, to misplaced parts during SMT P&P and soldering errors. Testing is a whole specialized branch in the electronics industry. Adafruit has made a few video's about how they test their own production, and how they design their test jigs.