Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mockito is calling real function instead of calling mocked function #3239

Open
sbmvirdi opened this issue Jan 20, 2024 · 0 comments
Open

Mockito is calling real function instead of calling mocked function #3239

sbmvirdi opened this issue Jan 20, 2024 · 0 comments

Comments

@sbmvirdi
Copy link

I am trying to mock rest template function but its actually trying to call the actual endpoint instead of giving back mock response

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@activeprofiles("test")
@AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@testcontainers

@MockBean
RestTemplate restTemplate;

        HttpHeaders headers = createHeader();
    String url = generateBaseUrlForUmsController(CREATE_USER, true);
    Mockito.when(restTemplate.postForEntity(
            eq(connectionConfig.getKeycloakTokenUrl()),
            any(HttpEntity.class),
            eq(AccessTokenResponse.class)
    )).thenReturn(ResponseEntity.ok().body(generateTokenResponse()));
    var request = CreateUserRequestDTO.builder()
            .firstName("John")
            .lastName("Doe")
            .teamId(UUID.fromString(teamId))
            .email("john@example.com")
            .build();
    var response = testRestTemplate.exchange(
            url,
            HttpMethod.POST,
            new HttpEntity<>(request, headers),
            UserResponseDTO.class
    );

    Assertions.assertEquals(HttpStatus.OK, response.getStatusCode());
    Assertions.assertNotNull(response.getBody());
    userId = response.getBody().getId().toString();
    
    Actual api called in my API
    
                ResponseEntity<AccessTokenResponse> response = restTemplate.postForEntity(apiUrl, entity, AccessTokenResponse.class);

Url i have verified that url passing to mockito and configured in API are same.
rest all params are also same.

getting exception
15:36:30.025 5b9d5379-9a6a-428a-82dd-37b254e2e925 [http-nio-auto-1-exec-9] ERROR c.l.ums.gateway.KeycloakService trace-id=5b9d5379-9a6a-428a-82dd-37b254e2e925 - Exception occurred due to: I/O error on POST request for "http://localhost:8080/realms/realm-name/protocol/openid-connect/token": Connection refused

I have configured localhost url in spring profile and it is trying to call the actual api so getting connection refused.

Build.Gradle:

plugins {
id 'java'
id 'org.springframework.boot' version '3.1.6'
id 'io.spring.dependency-management' version '1.1.4'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
sourceCompatibility = '17'
}

apply plugin: 'jacoco'
apply plugin: 'pmd'
apply plugin: 'checkstyle'

configurations {
compileOnly {
extendsFrom annotationProcessor
}
}

ext {
set('testcontainersVersion', "1.18.0")
}

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.flywaydb:flyway-core'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0'
implementation 'org.apache.httpcomponents.client5:httpclient5:5.2'
implementation 'org.keycloak:keycloak-admin-client:23.0.4'
testImplementation 'org.projectlombok:lombok:1.18.28'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-docker-compose'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.junit.jupiter:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
}

tasks.withType(Checkstyle).configureEach {
reports {
xml.required = true
html.required = true
}
}

tasks.withType(Pmd).configureEach {
reports {
xml.required = true
html.required = true
}
}

pmd {
consoleOutput = true
toolVersion = "6.33.0"
rulesMinimumPriority = 2
ruleSets = ["category/java/errorprone.xml", "category/java/bestpractices.xml"]
}

dependencyManagement {
imports {
mavenBom "org.testcontainers:testcontainers-bom:${testcontainersVersion}"
}
}

jacocoTestReport {
afterEvaluate {
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it,
exclude: ['com/example/ums/constants',
'com/example/ums/enums',
'com/example/ums/exception'])
}))
}
reports {
xml.required = true
csv.required = false
html.outputLocation = file("${projectDir}/build/reports/tests/coverage")
}
}

test {
useJUnitPlatform()
finalizedBy jacocoTestReport
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant