Pulsars are the most stable macroscopic clocks found in nature. Spinning with periods as short as a few milliseconds, their stability can supersede that of the best atomic clocks on Earth over timescales of a few years. Stable clocks are synonymous with precise measurements, which is why pulsars play a role of paramount importance in testing fundamental physics. As a pulsar rotates, the radio beam emitted along its magnetic axis appears to us as pulses because of the lighthouse effect. Thanks to the extreme regularity of the emitted pulses, minuscule disturbances leave particular fingerprints in the times-of-arrival (TOAs) measured on Earth with the technique of pulsar timing. Tiny deviations from the expected TOAs, predicted according to a theoretical timing model based on known physics, can therefore reveal a plethora of interesting new physical effects. Pulsar timing can be used to measure the dynamics of pulsars in compact binaries, thus probing the post-Newtonian expansion of general relativity beyond the weak field regime, while offering unique possibilities of constraining alternative theories of gravity. Additionally, the correlation of TOAs from an ensemble of millisecond pulsars can be exploited to detect low-frequency gravitational waves of astrophysical and cosmological origins. We present a comprehensive review of the many applications of pulsar timing as a probe of gravity, describing in detail the general principles, current applications and results, as well as future prospects.