|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Oracle and/or its affiliates. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package io.helidon.docs.mp.testing; |
| 17 | + |
| 18 | +import io.helidon.microprofile.testing.junit5.AddBean; |
| 19 | +import io.helidon.microprofile.testing.junit5.HelidonTest; |
| 20 | +import io.helidon.microprofile.testing.mocking.MockBean; |
| 21 | + |
| 22 | +import jakarta.inject.Inject; |
| 23 | +import jakarta.ws.rs.GET; |
| 24 | +import jakarta.ws.rs.Path; |
| 25 | +import jakarta.ws.rs.client.WebTarget; |
| 26 | + |
| 27 | +import org.junit.jupiter.api.Test; |
| 28 | +import org.mockito.Answers; |
| 29 | +import org.mockito.Mockito; |
| 30 | + |
| 31 | +import static org.hamcrest.MatcherAssert.assertThat; |
| 32 | +import static org.hamcrest.Matchers.is; |
| 33 | + |
| 34 | +@SuppressWarnings("ALL") |
| 35 | +class HelidonMockingSnippets { |
| 36 | + |
| 37 | + // tag::snippet_1[] |
| 38 | + @HelidonTest |
| 39 | + @AddBean(MockBeanAnswerTest.Resource.class) |
| 40 | + @AddBean(MockBeanAnswerTest.Service.class) |
| 41 | + class MockBeanAnswerTest { |
| 42 | + |
| 43 | + @MockBean(answer = Answers.CALLS_REAL_METHODS) // <1> |
| 44 | + private Service service; |
| 45 | + @Inject |
| 46 | + private WebTarget target; |
| 47 | + |
| 48 | + @Test |
| 49 | + void injectionTest() { |
| 50 | + String response = target.path("/test").request().get(String.class); |
| 51 | + assertThat(response, is("Not Mocked")); // <2> |
| 52 | + Mockito.when(service.test()).thenReturn("Mocked"); |
| 53 | + response = target.path("/test").request().get(String.class); |
| 54 | + assertThat(response, is("Mocked")); // <3> |
| 55 | + } |
| 56 | + |
| 57 | + @Path("/test") |
| 58 | + public static class Resource { |
| 59 | + |
| 60 | + @Inject |
| 61 | + private Service service; |
| 62 | + |
| 63 | + @GET |
| 64 | + public String test() { |
| 65 | + return service.test(); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + static class Service { |
| 70 | + |
| 71 | + String test() { |
| 72 | + return "Not Mocked"; |
| 73 | + } |
| 74 | + |
| 75 | + } |
| 76 | + } |
| 77 | + // end::snippet_1[] |
| 78 | +} |
0 commit comments