当我测试我的quarkus资源端点时,我的主服务被调用了



所以基本上我在src/test/java下有一个ResourceTest.class和MockService.class。ResourceFile类似于以下

@QuarkusTest
public class ResourceTest {
@Test
public void testFetch()  {

given().queryParam("fromTime", 0)
.queryParam("toTime", 0)
.queryParam("skip", 0)
.queryParam("limit", 5)
.queryParam("search", "")
.port(80)
.when().get("http://localhost/fetch")
.then()
.statusCode(200)
.body( is(CompletableFuture.completedFuture(BaseResponse.create(true, "Fetched.", Utils.populatePages(list,0,5,5)))));
}
}

我的模拟服务文件如下所示。。

@Mock
@ApplicationScoped
public class MockService extends Service {
@Override
public CompletableFuture<BaseResponse> fetch(String encounterId, String providerId, String patientId, long fromTime, long toTime, int skip, int limit, String search, Boolean isResolve) {

return CompletableFuture.completedFuture(BaseResponse.create
(true, "Fetched.", Utils.populatePages(list, 0, 5, 5)));
}
}

每当我运行testFetch((方法时,就会调用我的主服务文件,而不是MockServicefile。。我应该怎么做才能让我的mockService被调用。。?

在使用io.quarkus.test.junit.QuarkusMock时,对于作用域CDI bean,您应该更喜欢每次测试mocks注入,而不是@Mockbean替换。

Quarkus提供了与Mockito的开箱即用集成,允许使用io.quarkus.test.junit.mockito.@InjectMock注释模拟CDI范围的bean。

@QuarkusTest
public class ResourceTest {
@InjectMock
MockService mockService;
@BeforeEach
public void setup() {
// Here you can override the wide mock bean behavior per-each test
Mockito.when(mockService.fetch(any(),any(),any(),any(),any(),any(),any(),any(),any())).thenReturn(CompletableFuture.completedFuture(BaseResponse.create
(true, "Fetched.", Utils.populatePages(list, 0, 5, 5))));
}
@Test
public void testFetch()  {

given().queryParam("fromTime", 0)
.queryParam("toTime", 0)
.queryParam("skip", 0)
.queryParam("limit", 5)
.queryParam("search", "")
.port(80)
.when().get("http://localhost/fetch")
.then()
.statusCode(200)
.body( is(CompletableFuture.completedFuture(BaseResponse.create(true, "Fetched.", Utils.populatePages(list,0,5,5)))));
}
//@Mock: No @Mock annotation needed
@ApplicationScoped
public class MockService extends Service {
@Override
public CompletableFuture<BaseResponse> fetch(String encounterId, String providerId, String patientId, long fromTime, long toTime, int skip, int limit, String search, Boolean isResolve) {
// Here you can have your wide-test methods mock implementations
return CompletableFuture.completedFuture(BaseResponse.create
(true, "Fetched.", Utils.populatePages(list, 0, 5, 5)));
}
}
}

不要忘记包括quarkus-junit5-mockito集成工件:

<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-mockito</artifactId>
<scope>test</scope>
</dependency>

最新更新