Cognizant & Infosys Automation Interview Questions

These are real automation testing interview questions from Cognizant and Infosys, with a model answer — and code where you'd be expected to write it — for each one. Both companies follow a similar process: a technical round, a coding or practical round, and an HR round. The Infosys interview targeted candidates with roughly 2–8 years of experience.

Advertisement

Technical Round — Framework, Selenium & API

Explain your project, your role and your automation framework. (Both)

Start with a short introduction covering the application's domain, your role, team responsibilities and technology stack.

Sample short project introduction:

"I work on an e-commerce web application where customers search for products, add them to the cart and place orders. My responsibilities include functional testing, Selenium automation in Java, API validation, defect reporting and end-to-end quality checks before each release."

After the introduction, walk the interviewer through your automation framework.

Cover:

  • Framework type
  • Programming language
  • Selenium and testing tools
  • Maven and dependency management
  • Base classes
  • Driver factory
  • Page Object Model
  • Test classes
  • Test data
  • Configuration management
  • Reporting
  • CI/CD integration
  • Parallel execution
  • How you handle failures and flaky tests

The important thing is to explain your actual contribution, rather than describing a generic framework.

See Explain Your Automation Framework.

Explain the Page Object Model. (Cognizant)

The Page Object Model (POM) is a design pattern where each application page is represented by a separate class.

The page class contains:

  • Locators
  • Page-specific actions
  • Reusable methods related to that page

Test classes call these methods instead of directly interacting with Selenium elements.

For example:

public class LoginPage {

    private WebDriver driver;

    private By username = By.id("username");
    private By password = By.id("password");
    private By loginButton = By.id("login");

    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }

    public void enterUsername(String value) {
        driver.findElement(username).sendKeys(value);
    }

    public void enterPassword(String value) {
        driver.findElement(password).sendKeys(value);
    }

    public void clickLogin() {
        driver.findElement(loginButton).click();
    }
}

The test can then use:

LoginPage loginPage = new LoginPage(driver);

loginPage.enterUsername("testuser");
loginPage.enterPassword("password");
loginPage.clickLogin();

The main advantage is maintainability. If a locator changes, you generally update it in the page class rather than changing every test that uses it.

See Frameworks & POM.

Implicit wait vs explicit wait? (Cognizant)

An implicit wait applies globally to element searches.

An explicit wait waits for a particular condition, such as:

  • Element visibility
  • Element to be clickable
  • Element presence
  • Alert to appear
  • URL to contain a value

For example:

WebDriverWait wait =
        new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement loginButton =
        wait.until(ExpectedConditions.elementToBeClickable(
                By.id("login")));

loginButton.click();
Implicit Wait Explicit Wait
Global Specific condition
Applies to element searches Applied where needed
Less flexible More flexible
Can make timing behavior harder to reason about Better for targeted synchronization

For most automation frameworks, explicit waits provide better control.

Avoid mixing implicit and explicit waits, because their interaction can lead to confusing timeout behavior.

See Implicit vs Explicit vs Fluent Wait.

Explain TestNG integration. How do you capture screenshots only for failed tests? (Infosys)

TestNG handles test execution through features such as:

  • Annotations
  • Groups
  • Data providers
  • Assertions
  • Listeners
  • Parallel execution
  • testng.xml

Maven can execute TestNG through the Maven Surefire Plugin.

For failure screenshots, implement ITestListener and take a screenshot inside onTestFailure().

public class ScreenshotListener implements ITestListener {

    @Override
    public void onTestFailure(ITestResult result) {

        WebDriver driver = DriverFactory.get();

        File src = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);

        try {
            Path dir = Files.createDirectories(
                    Paths.get("screenshots"));

            Files.copy(
                    src.toPath(),
                    dir.resolve(result.getName() + ".png"),
                    StandardCopyOption.REPLACE_EXISTING
            );

        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

Register the listener using:

@Listeners(ScreenshotListener.class)

Alternatively, register it through testng.xml.

See TestNG Interview Questions.

How do you test an API end to end? (Cognizant)

Don't test only individual API calls. Test the complete business workflow.

For example:

  1. Authenticate and obtain a token.
  2. Create a resource using POST.
  3. Retrieve the resource using GET.
  4. Update it using PUT or PATCH.
  5. Delete the resource.
  6. Verify that the resource no longer exists.
  7. Validate the expected 404 response after deletion.

At every step, validate:

  • HTTP status code
  • Response body
  • Required fields
  • JSON schema
  • Headers
  • Response time
  • Authentication
  • Business rules

Also include negative scenarios such as:

  • Invalid authentication
  • Missing mandatory fields
  • Invalid data types
  • Invalid IDs
  • Unauthorised access
  • Duplicate data
  • Unsupported HTTP methods

See The Complete API Testing Tutorial.

What common errors do you see while testing APIs? (Cognizant)

Some common HTTP responses include:

Status Code Meaning Typical Testing Scenario
400 Bad Request Invalid or missing request data
401 Unauthorized Missing, invalid or expired authentication
403 Forbidden User doesn't have permission
404 Not Found Invalid endpoint or missing resource
405 Method Not Allowed Wrong HTTP method
415 Unsupported Media Type Incorrect or missing Content-Type
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Unexpected server-side failure
503 Service Unavailable Service temporarily unavailable

Other problems you may encounter include:

  • Request timeouts
  • Schema mismatches
  • Backend changes breaking existing tests
  • Invalid test data
  • Duplicate test data
  • Authentication failures
  • Dependency-service failures

How do you modify JSON request data? (Cognizant)

Instead of editing raw JSON strings for every test, create the request body using a POJO or a Map.

For example:

Map<String, Object> payload = new HashMap<>();

payload.put("name", "Asha");
payload.put("job", "SDET");

payload.put("job", "Lead SDET");

given()
    .contentType(ContentType.JSON)
    .body(payload)
.when()
    .post("/users")
.then()
    .statusCode(201);

This approach makes it easier to change individual fields for different test scenarios.

For larger frameworks, POJOs are often preferable because they provide stronger structure and type safety.

How do you add authentication to an API request? (Cognizant)

The approach depends on the authentication mechanism.

Bearer token / JWT:

given()
    .header("Authorization", "Bearer " + token);

Basic authentication:

given()
    .auth()
    .preemptive()
    .basic("user", "password");

OAuth 2.0:

given()
    .auth()
    .oauth2(accessToken);

See REST Assured Authentication.

Coding / Practical Round

Reverse each word in a string. (Cognizant)

The requirement is to reverse the characters of each word while keeping the word order unchanged.

public static String reverseEachWord(String sentence) {

    StringBuilder out = new StringBuilder();

    for (String word : sentence.trim().split("\\s+")) {
        out.append(new StringBuilder(word).reverse())
           .append(' ');
    }

    return out.toString().trim();
}

Example:

Input:  Java for testers
Output: avaJ rof sretset

Find duplicate words in a string. (Cognizant)

Use one set to track words that have already appeared and another set to store duplicates.

public static Set<String> duplicateWords(String sentence) {

    Set<String> seen = new HashSet<>();
    Set<String> dups = new LinkedHashSet<>();

    for (String word :
            sentence.toLowerCase().split("\\s+")) {

        if (!seen.add(word)) {
            dups.add(word);
        }
    }

    return dups;
}

Example:

Input:  the cat saw the other cat
Output: [the, cat]

LinkedHashSet is used for the duplicate set so that the order in which duplicate words are first identified is preserved.

Longest substring without repeating characters. (Cognizant)

A sliding-window approach with a HashMap can solve this efficiently.

public static int longestUniqueSubstring(String s) {

    Map<Character, Integer> lastSeen = new HashMap<>();

    int best = 0;
    int start = 0;

    for (int i = 0; i < s.length(); i++) {

        char c = s.charAt(i);

        if (lastSeen.containsKey(c)
                && lastSeen.get(c) >= start) {

            start = lastSeen.get(c) + 1;
        }

        lastSeen.put(c, i);

        best = Math.max(best, i - start + 1);
    }

    return best;
}

Example:

Input:  abcabcbb
Output: 3

The longest substring without repeating characters is "abc", which has a length of 3.

Automate a calendar date picker. (Cognizant)

For a calendar widget, first open the date picker, then move through the months until the target month is displayed.

Always put a guard on the loop so a wrong target cannot create an infinite loop.

public void selectDate(String targetMonthYear, String day) {

    driver.findElement(By.id("datepicker")).click();

    int guard = 0;

    while (!driver.findElement(
            By.className("ui-datepicker-title"))
            .getText()
            .equals(targetMonthYear)) {

        if (guard++ > 24) {
            throw new IllegalStateException(
                    "Month not found: " + targetMonthYear);
        }

        driver.findElement(
                By.cssSelector("a[title='Next']"))
                .click();
    }

    driver.findElement(
            By.xpath(
                "//table[contains(@class,'ui-datepicker-calendar')]"
                + "//a[text()='" + day + "']"
            )
    ).click();
}

Example:

selectDate("October 2026", "15");

If the date field is a normal editable input rather than a custom date picker, sendKeys() may be much simpler:

driver.findElement(By.id("date"))
      .sendKeys("15/10/2026");

Mention both approaches in an interview and explain that the implementation depends on the application's date-picker behavior.

Read data from an Excel file. (Cognizant)

Apache POI can be used to read Excel test data.

try (FileInputStream fis =
         new FileInputStream(
             "src/test/resources/testdata.xlsx");
     Workbook workbook = new XSSFWorkbook(fis)) {

    Sheet sheet = workbook.getSheet("Login");

    DataFormatter formatter = new DataFormatter();

    for (Row row : sheet) {

        if (row.getRowNum() == 0) {
            continue;
        }

        String username =
                formatter.formatCellValue(
                    row.getCell(0));

        String password =
                formatter.formatCellValue(
                    row.getCell(1));

        System.out.println(
                username + " / " + password);
    }
}

DataFormatter is useful because it allows different Excel cell types to be read as formatted text.

See Data-Driven Testing with Apache POI.

First collect all anchor elements, extract their href attributes, and then send HTTP requests to the URLs.

List<WebElement> links =
        driver.findElements(By.tagName("a"));

for (WebElement link : links) {

    String url = link.getAttribute("href");

    if (url == null || !url.startsWith("http")) {
        continue;
    }

    HttpURLConnection conn =
            (HttpURLConnection)
            URI.create(url)
                .toURL()
                .openConnection();

    conn.setRequestMethod("HEAD");
    conn.setConnectTimeout(5000);

    int code = conn.getResponseCode();

    if (code >= 400) {
        System.out.println(
                "Broken (" + code + "): " + url);
    }

    conn.disconnect();
}

Some servers reject HEAD requests even though the URL itself is valid.

In a real framework, retry those URLs with GET before reporting them as broken.

Also consider excluding:

  • mailto: links
  • javascript: links
  • Empty href values
  • Internal links that require authentication

HR Round — Infosys

The HR round generally focuses on your motivation, expectations, availability and overall fit.

Why do you want to change jobs?

Keep the answer positive and professional.

You can focus on:

  • Career growth
  • New technical challenges
  • Greater ownership
  • Larger-scale automation
  • Exposure to new technologies
  • Opportunities to work on product quality and engineering

Avoid criticising your current employer, manager or team.

What are your salary expectations?

Give a researched range based on your experience, current compensation, role requirements and market conditions.

Avoid giving an arbitrary number without understanding the position.

See SDET Salary Negotiation.

What is your notice period?

State your actual notice period clearly.

If it is negotiable or you have an early-release option, mention that separately.

For example:

"My official notice period is X days. I can discuss an early release if required, depending on the transition requirements of my current team."

From Real Projects

In interviews for testing and automation roles, I've found the questions come back to real work: the application you tested, how you wrote and reviewed test cases, how you tracked execution and defects (for me, TestRail and Jira), and how your automation was structured (Selenium, Java, TestNG, POM and a business library). Prepare one short, honest example from your own projects for each topic on this page. On Apkope, prospect and customer data arrives from email, phone, social media and chatbots, so test scenarios had to cover every channel that feeds the same records. Practice explaining your framework in two minutes.

📚 Official documentation: ISTQB Glossary of testing terms

FAQs

What interview rounds do Cognizant and Infosys conduct?

The process can vary by role and hiring cycle, but the interview structure described here generally includes a technical round, a coding or practical round, and an HR round.

Technical discussions can cover your project, automation framework, Selenium, API testing, REST Assured and TestNG.

The practical or coding round may include Java programs, Selenium tasks, API scenarios or other role-specific exercises.

How do you capture screenshots only for failed tests?

Implement ITestListener and take the screenshot inside onTestFailure().

For example:

@Override
public void onTestFailure(ITestResult result) {

    WebDriver driver = DriverFactory.get();

    File screenshot =
            ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);

    // Save screenshot
}

Then register the listener using @Listeners or testng.xml.

Use Selenium to collect the page's links, extract each href, send an HTTP request to the URL and check the response status.

Generally, responses in the 400 or 500 range require investigation.

Remember that some servers reject HEAD requests, so a GET retry may be required before declaring a URL broken.

How should I prepare?

Focus on the areas most likely to expose your practical experience:

  • Rehearse your project explanation.
  • Be able to explain your automation framework from end to end.
  • Practice Java coding without relying on an IDE.
  • Revise Selenium waits and common exceptions.
  • Understand Page Object Model and framework design.
  • Practice API status codes and authentication.
  • Revise REST Assured.
  • Understand TestNG listeners and parallel execution.
  • Practice SQL queries.
  • Prepare real examples from your projects.

See The Complete SDET Interview Guide.