It is permissible to masturbate for the purpose of medical testing
Question

                I know masturbation is haraam in Islam. But if one want to check for the infertility, the laboratory people asking the sperm's of the man. We can't get the sperm without masturbating in the laboratory. So Please clear this issue as soon as possible. InshaAllah Allah will reward for U for this issue.
Praise be to Allah.Yes, that is permissible. It says in 
    Fataawa al-Shaykh ‘Abd al-‘Azeez ibn Humayd (may Allaah have mercy on him) that he was asked about that and he replied: 
There is nothing wrong with that so long as there is a need for it. Whoever masturbates without 
    there being a need for it should be punished. But this is for a need, which is to produce semen for testing and to find out the reason why this 
    person is not having children. The reason for that may rest with him or with his wife, so in this case there is nothing wrong with it in sha 
    Allah.
 From Fataawa al-Shaykh ‘Abd al-‘Azeez ibn 
    Humayd, p. 271.
 And Allaah knows best.