He has also pleaded not guilty to possession of a Baikal 9mm automatic pistol and three rounds of .38 calibre ammunition at the same address on June 15, 2011.
Donnelly presented himself to Coolock Garda Station the day after the shooting in a very emotional state and told gardai he had shot his friend.
He told gardai he was in shock at what had happened saying "he's my best mate gone, gone. We went everywhere together, now he's gone".
Donnelly told gardai he and the three other men had been drinking with that day went back to his apartment.
He said in an interview that "we got p***ed drunk" and that Mr Flanagan started waving a gun around. He said he had never seen his friend with a gun before and that he did not mention where he got it.
He said Mr Flanagan handed the gun to him but he did not think there were bullets in it.
"I said 'give us a go of it', gun goes off and I shot me mate," he told gardai in an interview.
He said he threw the gun in the bushes outside the apartment and told his daughter the next morning what had happened before telling gardai later that day. He also told gardai where he had thrown the gun.
Deputy State Pathologist Khalid Jabbar told Eileen O'Leary, prosecuting, the cause of death was a gunshot wound to the back of the neck.
He agreed with Patrick Marinan, defending, under cross-examination, that the muzzle of the gun was either in actual contact or close contact when it was fired.
Dr Jabbar further agreed there was no evidence of an assault and that the deceased was in a seated position when he was shot.
Ballistics expert Detective Garda Alan Curry told Ms O'Leary the firearm was found by a bush outside the apartment.
He said the weapon was Russian, had been re-barrelled and the serial number on the gun had been erased.
Det Garda Curry also said the gun was in poor condition but he fired it 100 times and it did not go off accidentally. He also told the court that he did all the tests and it passed every one of them.
Under cross-examination by John Fitzgerald, defending, he agreed that there was a step to carry out in order to make the gun safer, which was not done in this case.
The trial continues.