The first thing you need to determine is whether you're really looking at your dog's testicles. When dogs get aroused, there are two glands, one on either side of the base of penis that become very large and firm/hard. I suspect this is what you're seeing and this normal for an aroused male. Once that's happened, placing him in a quiet, secure environment and allowing him to calm down will get things back to normal.
Re: how to prevent the problem in the first place, given today's technology it's doubtful that any dog is too small to neuter. However even if you do that may not stop the behavior because these animals may be aroused for territorial rather than sexual reasons. For example, many times people relate/react to little dogs as if they were babies, a form of communication that can be extremely stressful for some dogs because this actually communicates to the dog that he's responsible for protecting that person plus everything else. This is a difficult job for many big dogs, let alone little ones! Testosterone is one the the multiple hormones secreted when dogs are stressed and this and its side-effects--including erection, humping, etc.--may occur whether the animal is neutered or not.
Consequently, to help your dog the most I'd recommend looking at ways to relieve any stress that might be overly stimulating him and causing the behavior in the first place instead of focusing on eliminating any effects of this after-the-fact.
NOTICE: The information provided on this site is not a substitute for professional medical advice,
diagnosis, or treatment. Never delay or disregard seeking professional medical advice from your
physician or other qualified health provider because of something you have read on Wellsphere.
If you have a medical emergency, call your doctor or 911 immediately.