2016-08-29 128 views
1

這是我的類及其構造函數和依賴項。如何在控制器測試中注入依賴關係?

public class FavouriteProfilesController extends BaseController implements CurrentUser, JsonHelper { 

    private final UserProvider userProvider; 
    private MessagesApi msg; 

    @javax.inject.Inject 
    public FavouriteProfilesController(
      UserProvider userProvider, 
      MessagesApi msgApi) { 
     this.userProvider = userProvider; 
     this.msg = msgApi; 
    } 
    // methods etc... 

這是測試代碼,我剛剛從文檔複製:

public class FavouriteProfilesControllerTest extends WithApplication { 

    @Override 
    protected Application provideApplication() { 
     return new GuiceApplicationBuilder() 
       .configure("play.http.router", "javaguide.tests.Routes") 
       .build(); 
    } 

    @Test 
    public void testIndex() { 
     Result result = new FavouriteProfilesController().index(); // Inject dependencies here 
     assertEquals(OK, result.status()); 
     assertEquals("text/html", result.contentType().get()); 
     assertEquals("utf-8", result.charset().get()); 
     assertTrue(contentAsString(result).contains("Welcome")); 
    } 


} 

控制器有2只依賴,UserProvider和MessagesApi,我怎麼注入/他們嘲笑到控制器的測試?

回答

1

如果你使用的Mockito,你可以嘲笑他們是這樣的:

@RunWith(MockitoJUnitRunner.class) 
public class FavouriteProfilesControllerTest extends WithApplication { 

    @InjectMocks 
    private FavouriteProfilesController controller; 

    @Mock 
    private UserProvider userProvider; 

    @Mock 
    private MessagesApi msg; 

    @Test 
    public void test() { 
    Assert.assertNotNull(userProvider); 
    Assert.asserNotNull(msg); 
    } 
} 
+0

非常好,謝謝! –

1

的解決方案取決於您要測試的內容。如果你的意思是嘲笑UserProvider和MessageApi的整個行爲,那麼使用Mockito可能是一個合適的解決方案。 如果你想用真實物體測試控制器的功能,你需要注入真實的物體。這可能就像這樣:

public class FavouriteProfilesControllerTest extends WithApplication { 
    @Test 
    public void testIndex() { 
     running(Helpers.fakeApplication(),() -> { 
      RequestBuilder mockActionRequest = Helpers.fakeRequest(
       controllers.routes.FavouriteProfilesController.index()); 
      Result result = Helpers.route(mockActionRequest); 
      assertEquals(OK, result.status()); 
      assertEquals("text/html", result.contentType().get()); 
      assertEquals("utf-8", result.charset().get()); 
      assertTrue(contentAsString(result).contains("Welcome")); 
     }); 
    } 
} 

使用GuiceApplicationBuilder是沒有必要的,如果你不是說要使用不同的注射測試結合。調用Helpers.fakeApplication()調用默認的依賴注入。

您可以在Play here中找到更多關於單元測試的信息。

+0

謝謝,我會在家裏嘗試。 –

相關問題