3

我正在使用带有 Guice 的 play framework 2.1.4 将依赖项注入我的控制器。

在我的测试中,我想调用Helpers.callAction. 虽然controllers.routes.ref.Mycontroller不知道我的行为,因为它们不是静态的。

有没有办法以HandlerRef某种方式将其传递给callAction

谢谢

4

1 回答 1

0

我们最终使用 Jukito https://code.google.com/p/jukito/

它需要清理(我们可以为此创建自己的助手),但这是基本思想

@RunWith(JukitoRunner.class)
public class AuthenticationTest {
    @Inject
    private Authentication authentication;

    private String username = "username";
    private String password = "password";

    @Before
    public void setupMocks(UserDao mockedUserDao) throws RecordNotFoundException {
        ObjectNode json = Json.newObject();
        json.put("username", username);
        json.put("password", password);

        User mockedUser = mock(User.class);
        when(mockedUser.getEmail()).thenReturn("email@test.com");

        Http.RequestBody mockedBody = mock(Http.RequestBody.class);
        when(mockedBody.asJson()).thenReturn(json);

        Http.Request mockedRequest = mock(Http.Request.class);
        when(mockedRequest.body()).thenReturn(mockedBody);

        when(mockedUserDao.findByEmailAndPassword(anyString(), anyString())).thenReturn(mockedUser);

        Http.Context.current.set(new Http.Context((long) 1, mock(play.api.mvc.RequestHeader.class),
                mockedRequest, new HashMap<String, String>(), new HashMap<String, String>(),
                new HashMap<String, Object>()));
    }

    @Test
    public void loginTest(UserDao mockedUserDao) throws RecordNotFoundException {
        //Arrange
        FakeApplication app = Helpers.fakeApplication();
        start(app);

        ObjectNode json = Json.newObject();
        json.put("username", username);
        json.put("password", password);

        //act
        authentication.login();
        stop(app);

        //Assert
        verify(mockedUserDao).findByEmailAndPassword(anyString(), anyString());
        assertEquals(200, status(result));
    }
}
于 2013-10-18T04:01:41.070 回答