gpt4 book ai didi

java - 如何在 Controller 测试中注入(inject)依赖项?

转载 作者:行者123 更新时间:2023-11-30 02:49:15 25 4
gpt4 key购买 nike

这是我的类及其构造函数和依赖项。

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"));
}


}

Controller 有 2 个依赖项,UserProvider 和 MessagesApi,如何将它们注入(inject)/模拟到 Controller 测试中?

最佳答案

如果你使用 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);
}
}

关于java - 如何在 Controller 测试中注入(inject)依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39214096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com