Joseph was being tested, refined and matured; he was being taught during his spell as a slave, and in prison, to stay himself upon God, to remain cheerful and charitable in frustrating circumstances, and to wait patiently for the Lord. God uses sustained hardship to teach these lessons very frequently.