Representative Martha Roby of Alabama prevailed on Tuesday in a Republican primary election that unfolded as a test of fealty to President Trump, defeating a challenger who assailed her for withdrawing her support for Mr. Trump in the last days of the 2016 campaign.

Her criticism of Mr. Trump cost Ms. Roby, a mainstream conservative seeking a fifth term, a clear-cut victory in an initial round of voting last month. She fell short of a majority, forcing her to compete in a runoff election against Bobby Bright, a populist former Democrat who served in Congress and as mayor of Montgomery, Alabama’s capital.

She handily held off Mr. Bright, The Associated Press reported, after overcoming suspicion about her loyalty to the president with help from an unlikely ally — Mr. Trump himself.

Unlike other Republicans whom Mr. Trump has gleefully helped push from office, Ms. Roby was not an eager antagonist during the 2016 presidential election, or since. Though she pronounced Mr. Trump “unacceptable” after the release of the “Access Hollywood” recording that showed him bragging about groping women, she has been an unflagging supporter since his inauguration.