Furthermore, the Bath-sheba episode was a punishment for David's excessive self-consciousness. He had fairly besought God to lead him into temptation, that he might give proof of his constancy. It came about thus: He once complained to God: "O Lord of the world, why do people say God of Abraham, God of Isaac, God of Jacob, and why not God of David?" The answer came: "Abraham, Isaac, and Jacob were tried by me, but thou hast not yet been proved." David entreated: "Then examine me, O Lord, and try me." And God said: "I shall prove thee, and I shall even grant thee what I did not grant the Patriarchs. I shall tell thee beforehand that thou wilt fall into temptation through a woman."
David Begged God for a Test and Got Bathsheba
Legends of the Jews 4:53