Skip to content

Instantly share code, notes, and snippets.

@abhi2495
Last active July 19, 2020 20:31
Show Gist options
  • Save abhi2495/8d93be47753c1e3e39fdfd7fd2a3b375 to your computer and use it in GitHub Desktop.
Save abhi2495/8d93be47753c1e3e39fdfd7fd2a3b375 to your computer and use it in GitHub Desktop.
/*
##################################################################################
##################################################################################
######### IF YOU FOUND THIS GIST USEFUL, PLEASE LEAVE A STAR. THANKS. ############
##################################################################################
##################################################################################
*/
@RunWith(SpringRunner.class)
@WebFluxTest(controllers = {GreetingController.class})
@Import({WebSecurityConfiguration.class, TenantService.class, CacheConfiguration.class})
@ActiveProfiles(Application.Profiles.TEST)
@AutoConfigureWireMock(port = 0)
public class GreetingControllerTest {
private static final String TENANT_ALIAS = "foo";
private static final String TENANT_ID = "x-foo";
@MockBean
private GreetService greetService;
@Autowired
private WebTestClient webTestClient;
@BeforeClass
public static void setup() {
TestUtil.mockOAuthClientTokenResponse();
}
@Test
public void test_greetApi() throws JsonProcessingException {
Mockito.when(greetService.greet()).thenReturn(Mono.just("hello"));
Tenant tenant = new Tenant(TENANT_ID, TENANT_ALIAS);
stubFor(get(urlEqualTo("/tenantApi?alias=" + TENANT_ALIAS))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withBody(new ObjectMapper().writeValueAsString(Collections.singletonList(tenant)))));
webTestClient
.mutateWith(mockOidcLogin().authorities(new SimpleGrantedAuthority("SCOPE_greet")))
.get()
.uri(....greet api....)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("hello");
}
}

An example demonstrating usage of Spring's @WebFluxTest in Junit Tests

public final class TestUtil {
private static final String MOCK_TOKEN_RESPONSE = "{\n" +
" \"access_token\": \"eyJhbG\",\n" +
" \"expires_in\": 600,\n" +
" \"refresh_expires_in\": 1800,\n" +
" \"refresh_token\": \"eyJhbGc\",\n" +
" \"token_type\": \"bearer\",\n" +
" \"not-before-policy\": 0,\n" +
" \"session_state\": \"9de04c8c-1790-4336-b77a-b9b14c20d7c3\",\n" +
" \"scope\": \"greet\"\n" +
"}";
private TestUtil() {
}
public static void mockOAuthClientTokenResponse() {
stubFor(post(urlEqualTo("/.well-known/token"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withBody(MOCK_TOKEN_RESPONSE)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment