Follow-up on #1631: do some refactoring and add a test.