David Hamelech taught (Tehillim 11:5), “Hashem tests the tzaddik, but He despises a wicked person who loves larceny.” The passuk seems inconsistent, for it should state that Hashem “loves the tzaddik,” just as it says that He “despises” the wicked one. Therefore, the midrash explains that Hashem tests a tzaddik, but He despises testing a wicked person.
Rabi Yonasan said: This is comparable to a potter who makes earthenware: When he inspects his products, he doesn’t test those that are imperfect, with thin walls or with cracks, for they would break after tapping on them even once. So which utensils does He test? Those barrels that are whole and strong, those that he expects not to break even if he raps on them repeatedly. In the same way, Hashem does not bother testing the wicked, who cannot pass such a test; rather, He tests the righteous ones who can pass it, in order to reveal their righteousness. This is the meaning of the passuk, “Hashem tests the tzaddik” – just as the potter raps on pots to demonstrate that they are strong and will not break. And the Torah states (Bereishis 22:1), “And Hashem tested Avraham.”
Rabi Yosi ben Chanina taught that the goal of a nisayon is for the tzaddik to improve. This is comparable to a flax dealer: When he knows that his stalks of flax are of good quality, the more he beats them, the better they become. With each strike, the flax increases in value. And when he knows that his flax is not good, he cannot beat it even once without its breaking apart. In the same way, Hashem does not test the wicked but only the tzaddikim, as it says, “Hashem tests the tzaddik.”
Rabi Elazar said: Nisyonos come to the tzaddik, since he has the power to protect his generation, like a farmer who hitches a yoke only on a strong ox. If a farmer had two oxen, one strong and the other weak, on which one does he place a yoke? Wouldn’t he place it on the stronger one? Likewise, Hashem tests the tzaddikim, as it says, “Hashem tests the tzaddik.”
(Midrash Rabbah, Bereishis 32:3)