David knew what the Lord had done, saying,
You have tested my heart; You have visited me in the night; You have tried me and have found nothing; I have purposed that my mouth shall not transgress. (Psalms 17:3)
The Lord had tested David and he knew it, but he also knew that the Lord found no sin. How could that be? David purposed not to sin. He did not go through life haphazardly, but lived purposely and part of that included no sinning.
Did David ever sin? Yes, but those occasions were exceptions to the rule of life he had purposed for himself.