I'd extract this to a method, for which you can write a test.