BRAMPTON, Ont.—A Toronto security guard on trial for allegedly attempting to join the Somali terrorist group Al-Shabab said he believed it was his religious duty to do so, an undercover police officer testified on Tuesday.

“It’s the ultimate sacrifice you can make for your religion,” Mohamed Hassan Hersi said, according to the testimony of the officer, whose identity cannot be disclosed to due a publication ban. “Basically it’s God’s will.”

Three years after Mr. Hersi was arrested at Toronto’s Pearson Airport as he was about to board flights to London and Cairo, his trial is now underway and jurors are hearing from the undercover officer who befriended the Somali-Canadian.

The trial comes amid concern over the radicalization of Canadians — dozens of whom have joined Islamist terror groups in the Middle East and Africa. Al-Shabab was behind last year’s massacre at the Westgate shopping mall in Nairobi that left two Canadians dead.