Injecting objects from the test into components

Sometimes, particularly for unit tests, you will want to specifically control which objects that are injected into the page/component under test. Simply annotate the fields containing these objects with @ForComponents and, at the end of test setup, Testify will gather the objects and inject them into page/components in preference to the usual component injection chain.

In rare cases, for complex fakes, you may need access to Tapestry services in the fake; you can call TapestryTester#autobuild to create objects and have the constructor automatically called with services populated for the parameters.

It's easy to create mocks (or stubs) with mocking frameworks such as Mockito and EasyMock.

You can also use @ForComponents to pass any objects into the page/component - they don't need to exist as services in Tapestry IOC. This is particularly useful for testing components where you can use it to pass parameters from the test to the component (via a 'demo' page).

Note that you can change the value of a @ForComponents field at any point during setup or the tests and the pages/components will see the new value during the next page render.

public class MyTest extends AbstractMyApplicationTest {
    @ForComponents MyService service;
    @ForComponents("serviceId") MyNamedService namedService;

    protected void doSetUp() {
        service = new MyFakeService();
        namedService = new MyFakeNamedService();
    }
    
    public void testElementIsOnPage() {
        service.addFakeData(1,2,3);
        
        Document page = tester.renderPage("mypage");
        assertNotNull(page.getElementById("myid"));
    }
}