Al Shabaab militants rammed a car packed with explosives into a Somali army base southwest of the capital Mogadishu on Monday, killing at least 10 soldiers, the group and a military officer said.
The assault on the base 50 km outside Mogadishu was part of the group's campaign to try to topple the Western-backed government.
"Heavy exchange of gunfire continued for hours," Major Ahmed Farah told Reuters from the nearby town of Afgooye. At least 12 Al Shabaab fighters were killed, he added.
Al Shabaab spokesman Abdiasis Abu Musab said 30 soldiers had been killed in the raid that lasted several hours before his group withdrew. He did not mention Al Shabaab casualties.
The group often cites a higher death toll than officials.
The attack came days after Somalia's government claimed that they destroyed an Al Shabaab base used to store supplies in a region south of Mogadishu.
The militant group has struck multiple targets in recent weeks. On July 1, six people were killed in Kenya when Al Shabaab gunmen sprayed two buses with bullets near the Somali border.
Last month, a suicide bomber blew himself up at a hotel in Mogadishu, killing 15 people.
The United States and other Western countries have been among the biggest donors to the Somali government which is slowly rebuilding the country after years of conflict.
The attack also comes as Somalia prepares to hold parliamentary and presidential elections later this year.
The vote planned for August will be by limited franchise rather than the one-person-one-vote system, which officials and diplomats say would be too difficult to implement while fighting the ongoing insurgency.