Level:
No questions match — try other words or turn a level back on.
1
What do you understand by a unit test, and what exactly does it check?
A unit test checks the smallest piece of code (usually one class or method) quickly, in isolation from the outside world. No database, network or file system is involved.
2
In JUnit 5, when are the @BeforeEach and @AfterEach methods called, and how many times?
@BeforeEach runs before every @Test method, and @AfterEach runs after each one. If the class has 5 tests, each of them runs 5 times.
3
Why is a method marked with @BeforeAll usually static?
By default JUnit 5 creates a new instance of the class for every test. @BeforeAll runs once before all the tests, when no instance exists yet, so it has to be static.
4
In what order do you pass the expected and actual values to assertEquals, and what does it affect?
In JUnit the first argument is the expected value and the second is the actual one. If you swap them the test still works correctly, but the failure message comes out confusing.
5
How do you check in JUnit 5 that a method throws an exception in the right situation?
Use assertThrows(ExceptionType.class, () -> ...). It fails the test if the code in the lambda doesn't throw an exception of that type, and it returns the thrown exception, so you can check its message too.
6
How does the Arrange-Act-Assert (or Given-When-Then) pattern structure a test?
The test is split into three parts: preparing the data and objects, performing the one action under test, and checking the result. That way you can see at a glance what situation the test covers.
7
What is a mock object in a test, and why do you need one?
A mock is a fake object put in place of a real dependency: in the test you decide what it returns, and afterwards you can check how it was called. You need it to isolate things that are slow or that you can't control, like a database or an external API.
8
In Mockito, what actually happens when you write when(...).thenReturn(...)?
The call inside when is "recorded" on the mock, and thenReturn sets what later calls with those arguments will return. Calls you haven't stubbed return a default value: null, 0, false, or an empty collection.
9
What does verify() check in Mockito, and when do you use it?
verify checks whether a method on a mock was called, how many times, and with which arguments. It's used for actions that return no result but have an effect on the outside.
10
How do the @Mock and @InjectMocks annotations differ?
@Mock creates a fake object for a dependency. @InjectMocks creates an instance of the real class under test and places the mocks from the test class into it, through the constructor, a setter or a field.
11
Explain the main difference between a unit test and an integration test with an example.
A unit test checks one class without its dependencies, while an integration test checks that several parts work together, for example a service, a repository and a real database. The first is fast, the second slower but finds real problems.
12
What does the idea of the test pyramid mean?
The idea is that most of your tests should be fast, cheap unit tests, with fewer integration tests in the middle and very few end-to-end tests at the top. The higher you go, the slower, more expensive and more brittle the tests get.
13
What do you pay attention to when naming test methods, and why is @DisplayName useful?
A test name should say what is expected in which situation, for example bosh_savatda_chegirma_qollanmaydi. @DisplayName shows a readable name in the report, with spaces and any characters.
14
What does @ParameterizedTest give you, and which sources do you know for it?
It runs one test method several times with different inputs. The data comes from sources such as @ValueSource, @CsvSource, @MethodSource and @EnumSource.
15
When is it reasonable to use the @Disabled annotation, and what makes it risky?
@Disabled switches a test off temporarily, for example while an external service is down. The risk is that a disabled test gets forgotten, and the bug it was supposed to catch quietly goes to prod.
16
What does test coverage measure, and does 100% coverage mean the code has no bugs?
Coverage shows how many lines or branches of code were executed while the tests ran. Even at 100% there can be bugs: the code may have been executed, but the result may never have been checked by any assert.
17
Why should tests not depend on each other, and be able to pass in any order?
JUnit doesn't guarantee a run order, and it can run tests in parallel. If one test relies on a state left by another, it fails when the order changes or when you run it alone.
18
Where do you write tests in a Maven project, and how does mvn test find them?
Tests live in src/test/java and test resources in src/test/resources. mvn test uses the Surefire plugin to find classes whose names end in *Test, Test*, *Tests or *TestCase and run them.
19
When is assertAll better than ordinary sequential asserts?
Ordinary asserts stop at the first failure. assertAll runs every check and shows all the failures together, which is handy when checking several fields of one object.
20
What is TDD, and how does the red-green-refactor cycle work?
TDD means first writing a failing test, then writing the simplest code that makes it pass, then cleaning the code up. Each step is small, and the code always grows protected by tests.
21
How would you explain the difference between a mock, a stub, a spy and a fake?
A stub only returns a canned answer, while a mock also lets you verify calls. A spy wraps a real object and replaces some of its methods. A fake is a simplified but working implementation, for example an in-memory repository.
22
When working with a spy, why does the following stubbing give an unexpected result, and how do you fix it?
When you write when(spy.get(0)), get(0) is called on the real list, and an empty list throws IndexOutOfBoundsException. For a spy you have to write doReturn("x").when(spy).get(0), which doesn't call the real method.
23
When Mockito throws UnnecessaryStubbingException, what does that mean, and what's the right fix?
MockitoExtension runs in strict stubs mode by default: if the test stubs a method that is never called, the test fails. This usually points to a redundant stub, or one written with the wrong argument.
24
In Mockito, what happens if you mix any() with an exact value in one call?
Mockito throws InvalidUseOfMatchersException: if a matcher is used for one argument, all the other arguments have to be matchers too. You fix it by wrapping the exact value in eq(...).
25
When do you need ArgumentCaptor, and what can you use instead?
ArgumentCaptor catches an argument passed to a mock so you can inspect its contents in detail, especially when the object is created inside the method. For simple cases argThat or eq is enough.
26
If the code calls LocalDateTime.now() inside, how do you reliably test time-dependent logic?
Instead of getting the time directly, you pass java.time.Clock in as a dependency: Clock.systemDefaultZone() in prod and Clock.fixed(...) in the test. That way the test gives the same result for any date and time.
27
What main changes do you run into when moving from JUnit 4 to JUnit 5?
The package org.junit became org.junit.jupiter.api, @Before/@After became @BeforeEach/@AfterEach, a single @ExtendWith replaced @RunWith and @Rule, and assertThrows replaced @Test(expected). Old tests can keep running alongside through the Vintage engine.
28
What do @Nested test classes give you, and how are they structured?
@Nested groups tests by state or scenario using inner (non-static) classes. Each inner class inherits the outer class's @BeforeEach and adds its own.
29
Should you test private methods separately? Justify your view.
Usually no: a private method is tested through the public methods, because it's an implementation detail. If testing a private method on its own feels really necessary, it's often logic that should be moved into a separate class.
30
How do the PER_METHOD and PER_CLASS modes of the test instance lifecycle differ in JUnit 5?
PER_METHOD (the default) creates a new instance of the class for every test, so fields aren't shared between tests. PER_CLASS uses one instance for all the tests: @BeforeAll doesn't have to be static, but state can leak between tests.
31
How does @SpringBootTest differ from slice tests like @WebMvcTest and @DataJpaTest, and which do you choose when?
@SpringBootTest starts the whole application context: slow, but everything is real. Slice tests load only the beans of one layer: @WebMvcTest loads controllers and MVC, @DataJpaTest loads JPA and repositories. They're faster and pin down a failure more precisely.
32
How do you test a REST controller with @WebMvcTest and MockMvc?
@WebMvcTest(Controller.class) loads only that controller, and the service dependencies are mocked. With MockMvc you send a request as if it were a real HTTP request and check the status, headers and JSON body; no server port is opened.
33
What does @MockitoBean (formerly @MockBean) do in Spring tests, and what does heavy use of it cost?
It replaces a bean in the Spring context with a Mockito mock. Each different set of mocks changes the context configuration, so Spring can't reuse the cached context and starts a new one, which slows the test suite down sharply.
34
What settings does @DataJpaTest run with by default, and what traps does that lead to?
By default it replaces the real DataSource with an embedded database, makes each test @Transactional with a rollback at the end, and turns on SQL logging. As a result, many bugs stay hidden because of H2 dialect differences and because nothing gets flushed.
35
What is Testcontainers, and why do you often pick it over H2 for integration tests?
Testcontainers starts Docker containers (PostgreSQL, Kafka, Redis and others) from inside the test and removes them when the test ends. You test against a real database of the same version as in prod, which eliminates false green results caused by dialect differences.
36
What bugs can stay hidden when you put @Transactional on an integration test?
The test and the service run in one transaction that rolls back at the end. So lazy loading errors, constraint violations at commit time, and the service's own transaction boundaries all stay invisible, and then show up in prod.
37
How do you prepare data for tests, and what are test data builders and the Object Mother approach for?
Instead of assembling a big object by hand in every test, you use a builder or factory methods with default values: the test changes only the field that matters to it. That keeps tests short, and when a new required field is added, only one place changes.
38
If your service calls an external HTTP API, how do you test that integration?
Instead of mocking the client class, it's better to start a fake HTTP server: WireMock or Spring's MockRestServiceServer. Then the URL, headers, JSON parsing, timeouts and handling of 5xx errors are all checked through the real HTTP layer.
39
If a Testcontainers container runs on a random port, how do you pass its address into the Spring configuration?
In Spring Boot 3.1+, putting @ServiceConnection on the container field is enough: Boot picks up the connection details itself. For unsupported services or custom properties, use @DynamicPropertySource.
40
How do you wait for the result of an @Async method or a background process in a test, and why is Thread.sleep a bad choice?
Thread.sleep(2000) either waits too long, or isn't enough on a slow CI and the test fails by chance. Instead, with a tool like Awaitility you check at short intervals until the condition holds, and set a maximum time limit.
41
How does the Spring test context cache work, and why do tests suddenly slow down in a big project?
Spring caches a started context by its configuration key, and test classes with identical settings reuse it. A different @MockitoBean, profile, property or @DirtiesContext creates a new key, and each one starts a context from scratch.
42
What is a flaky test, what are its usual causes, and how do you find and fix one in CI?
A flaky test sometimes passes and sometimes fails even when the code hasn't changed. The causes are often dependence on time and order, shared state between tests, external systems, and hardcoded sleeps. To fix it, you first need to reproduce it reliably.
43
How does consumer-driven contract testing work between microservices, and how does it differ from an ordinary integration test?
The consumer service writes down, as a contract, what request it sends to the provider and what response it expects. The provider is verified against those contracts in its own CI. That way, an API change that would break a consumer is caught in advance, without starting the two services together.
44
In a class that has to be thread-safe, how do you try to catch a race condition with a test?
I use CountDownLatch or CyclicBarrier to start many threads at the same moment, run one operation thousands of times in parallel, and check the final invariant. But such a test doesn't prove there's no bug, it only raises the odds of finding it; for serious cases you need jcstress.
45
What does mutation testing (for example, PIT) measure, and how does it complement line coverage?
PIT makes small changes to the code ("mutants"): it swaps > for >=, + for -, changes a return value. Then it checks whether the tests fail on that broken code. A surviving mutant means the tests didn't notice the change.
46
How do you speed up a suite of integration tests written with Testcontainers?
The main win is to start the container once per JVM instead of once per test class (the singleton pattern) and to keep a single Spring context. On top of that, lightweight images, local reuse, cleaning data with truncate, and splitting tests across parallel forks help.
47
When integration-testing a Kafka listener, how do you choose between EmbeddedKafka and Kafka in Testcontainers, and what do you watch for?
@EmbeddedKafka is fast and needs no Docker, but it's a broker inside the JVM, so its settings differ from prod. Testcontainers gives you a real broker image. Either way, since the listener works asynchronously, you wait for the result with Awaitility and check offset, retry and DLT behavior.
48
The test below always passes on a local machine but fails now and then on CI. What could be the cause?
The tests share a static cache, and the result depends on the order they run in. On top of that, HashSet iteration order isn't guaranteed, so comparing with toString() is wrong. You need to clean the state in every test and compare without regard to order.
49
What problems does too much mocking in tests (over-mocking) lead to, and where do you draw the line?
If every dependency is mocked, the test just replays the code's internal sequence of calls: on refactoring the test breaks even when behavior hasn't changed, and real integration bugs stay invisible. I mock only things at the boundary: network, time, external APIs.
50
How do you test endpoints protected by Spring Security, and where is @WithMockUser not enough?
@WithMockUser puts a ready-made user into the SecurityContext and is handy for checking role-based permissions. But it bypasses the authentication layer: JWT parsing, filters, token expiry. Those need to be checked separately with the .with(jwt()) post-processor or a real token.
51
How does @TestConfiguration differ from a plain @Configuration in the test folder, and why does a bean written for one test sometimes leak into other tests?
A top-level @TestConfiguration is excluded from component scanning and applies only in a test that @Imports it. A plain @Configuration in src/test/java, if it sits inside the application's package, gets in through scanning and lands in every @SpringBootTest.
52
When is @DirtiesContext really needed, and what does using it a lot cost?
When a test corrupts state inside the test context (a cache in a singleton bean, a scheduler, static configuration) in a way that can't be undone. Each time it's used, the context is evicted from the cache and the next test starts it from scratch.
53
How do you test code that works with @TransactionalEventListener(phase = AFTER_COMMIT)?
Because the test transaction ends with a rollback, an AFTER_COMMIT listener is never called at all. Either I write the test without @Transactional and wait for the result, or I commit inside the test with TestTransaction.flagForCommit() and TestTransaction.end(), then check the listener's effect.
54
What does a Mockito mock return from methods you haven't stubbed, and when does RETURNS_DEEP_STUBS become a trap?
By default (RETURNS_DEFAULTS): null for objects, 0/false for primitives, and an empty value for collections, Optional and Stream. RETURNS_DEEP_STUBS stubs a chain like a.getB().getC() in one line, but it hides a tangled design and nails the test to the internal structure.
55
How can Mockito mock static methods and final classes, and why should you be careful with it?
Since Mockito 5, the default "inline mock maker" is used: it rewrites a class's bytecode at runtime through a Java agent. That's why final classes and mockStatic work, but a static mock applies only in the current thread and inside a try-with-resources.
56
When do you need thenAnswer and doAnswer in Mockito? Show an example.
When the answer isn't known in advance and has to be computed from the call's arguments: returning the passed object with an ID, invoking a callback, simulating the side effect of a void method. But if the logic inside an answer grows, it's time to write a fake instead of a mock.
57
When does Testcontainers consider a container "ready", and how does a wrong wait strategy lead to flaky tests?
By default GenericContainer waits until the first exposed port starts listening (up to 60 seconds). But an open port doesn't mean the service is ready; so you need to wait on a log message, an HTTP health check or a Docker healthcheck.
58
What is @JsonTest for, and what bugs does testing JSON serialization separately catch?
@JsonTest starts only the Jackson layer: the ObjectMapper configured by Boot, the @JsonComponents and the modules. That way you can quickly check how date formats, null fields, BigDecimal and enum names will come out in prod, without a controller or a database.
59
How do you guarantee, in a test, the error format the API returns (ProblemDetail) for validation and business errors?
With @WebMvcTest and MockMvc, for each kind of error I check the status code, the application/problem+json content type and the fields in the response body. I specifically test that an unexpected exception returns 500 without exposing a stack trace or SQL text.
60
How do you check in a test that Flyway migrations and JPA entities match each other?
In tests Flyway, not Hibernate, should create the schema: migrations run on a real PostgreSQL (Testcontainers), and then spring.jpa.hibernate.ddl-auto=validate makes Hibernate check that the tables and columns of the entities exist in the database. If they don't match, the context won't start and the test fails immediately.
61
When is usingRecursiveComparison() useful in AssertJ, and what traps does it have?
It compares objects field by field instead of with equals: you can check an entity or DTO with no equals written against an expected object in a single line. The traps are excess ignoringFields, BigDecimal scale differences and Hibernate lazy proxies.
62
How do you test a job that runs with @Scheduled?
I separate the scheduling from the work itself: I test the job logic by calling the method directly, test the cron expression separately with CronExpression, and switch the scheduler off in the test profile, otherwise it fires on its own between tests and changes data.
63
In the service below, when rebuildAll() is called, does build() really run asynchronously, and which test catches that?
No: this::build bypasses the Spring proxy, so build runs synchronously on the calling thread. A plain unit test has no proxy and won't see this; only a test with a Spring context catches it, for example one that checks the name of the thread it ran on.
64
How does the JUnit 5 extension model work, and give an example of a case where you wrote an extension yourself.
JUnit 5 has extensions instead of runners and rules: they implement interfaces like BeforeEachCallback, ParameterResolver and TestExecutionExceptionHandler, and are called at the relevant point in the test lifecycle. They're attached to a class with @ExtendWith, and several can sit side by side without trouble.
65
How do you turn on running tests in parallel in JUnit 5, and what problems does it bring?
In junit-platform.properties you set junit.jupiter.execution.parallel.enabled=true and the modes. After that, tests with shared state (static fields, a shared database table, System.setProperty) start interfering with each other; you have to isolate them with @ResourceLock or @Isolated.
66
The tests pass when run alone but fail with the whole suite. How do you investigate?
This is almost always state that "leaked" between tests: a static field, an uncleaned database, a modified bean or a global setting. First I find the order, meaning which test has to run first for the failure to happen, then I isolate that pair and find the leftover state.
67
How do MockMvc, WebTestClient and TestRestTemplate on RANDOM_PORT differ, and how does that affect transactions?
MockMvc / WebTestClient / TestRestTemplate / RestClient — Server: none (mock servlet) / mock or real / real (RANDOM_PORT); Thread: the test thread / depends / a server pool thread; Filters, serialization: yes / yes / yes, with real HTTP; Effect of the test's @Transactional: reaches the controller / reaches it in mock…
68
How do you test that a method marked @Cacheable really answers from the cache, and that the cache is cleared on time?
In a Spring context I call the cached service twice and check that the repository or client underneath was called once; then that it's called again after the operation that does a @CacheEvict. If Redis is used, I test serialization and TTL separately against a real Redis in Testcontainers.
69
How do you test that code writes an important condition to the log (for example, a payment error or an audit entry), and when is that appropriate?
You can catch console output with Spring Boot's OutputCaptureExtension, or catch the log events that hit a specific logger with Logback's ListAppender, and check them. But if the log is a business requirement (audit), it's better to make it a separate dependency or a metric, because log text changes often.
70
How do you separate unit and integration tests in the build: how do Surefire and Failsafe differ, and when do you need JUnit @Tag?
Surefire runs the fast tests in the test phase, and Failsafe runs the *IT tests in the integration-test and verify phases. Failsafe reports a failure not immediately but in verify, so the post-integration-test cleanup step gets a chance to run. @Tag is for grouping independent of the name pattern.
71
For a new Spring Boot service, how do you decide the ratio of unit, slice and integration tests?
Not the classic pyramid; I go by the nature of the service: with a lot of complex domain logic, more unit tests; with a "glue" service that mostly reads and writes the database and external APIs, more integration tests with Testcontainers. The criterion: which test catches a bug the cheapest and most reliably.
72
The test stage in CI takes 25 minutes. How do you analyze it and cut it down?
First I measure: how many Spring contexts are started, which are the 20 slowest tests, how many times the containers start. Usually most of the time goes to the number of contexts and Docker containers started over and over; after that comes parallelism and sharding.
73
How do you test the transactional outbox pattern, so that no message is lost and sending one twice does no harm?
I check four things separately: that the business record and the outbox row are saved in one transaction or roll back together; that the relay doesn't lose rows if the broker goes down; that two relay instances don't pick up the same row twice; and that the consumer tolerates duplicates. All of it with a real database and broker, in tests without @Transactional.
74
How do you choose a database cleanup strategy between integration tests: rollback, TRUNCATE, or separate data per test?
At the repository level, the test transaction rollback is fast and enough. When a commit, another thread or RANDOM_PORT is involved, use a single TRUNCATE ... CASCADE before the test. If you need to run in parallel, the best approach is not to rely on cleanup at all: each test creates its own unique data.
75
Flaky tests have piled up on your team and developers have gotten used to pressing the "rerun" button. What do you do?
I move the flaky tests to a separate list (quarantine) to make the main pipeline reliable, give each an owner and a deadline, and make retries measurable rather than hidden. The goal is to restore trust in a red build.
76
Two parallel requests could redeem the same coupon twice. How do you reproduce such a database race in an integration test?
I line several threads up at a "start" with a CountDownLatch, call the same operation in parallel against a real database, and check the invariant: the coupon must have been used once. I run the test with many iterations, because the race doesn't show up every time.
77
How do you protect authorization rules (who can access which resource) from regressions?
For every endpoint I write a role-and-ownership "permission matrix" with parameterized tests: anonymous, an ordinary user, another user's resource, a moderator, an admin. I set it up so that a new endpoint that isn't in the matrix makes the test fail.
78
How do you test retry and idempotency logic when the error only shows up on a network failure?
I inject the failure on purpose: in WireMock, Fault.CONNECTION_RESET_BY_PEER, delays, and the "request was executed but the response got lost" case; with Toxiproxy, cutting the database or broker connection. Then I check: was the operation executed once, is the number of retries right, is the result consistent.
79
How does TDD affect design, and in which cases does strict TDD do harm instead of good?
Because the test is written first, the class is designed from the caller's point of view: dependencies are explicit, the API is small, side effects sit at the boundary. But in exploratory code where requirements are unclear, framework "glue" and fast-changing prototypes, strict TDD makes you spend time on tests that get thrown away.
80
You have to change a legacy module that has no tests at all. Where do you start?
First I write characterization tests that "freeze" the current behavior: whatever the code returns now is taken as the expected result. Then, with small, safe refactorings, I open up testable "seams", and only after that do I add the new feature with TDD.
81
In an organization with 15 teams and 60 services, how do you standardize the test strategy without choking the teams' independence?
I set a small "minimum" that's mandatory for everyone (contract tests, integration tests against a real database, a time limit in CI, a flaky policy), and recommend the rest through templates, a shared library and metrics. The rules are about outcomes, not about a specific tool.
82
Should you set a mandatory coverage threshold (say, 80%) for the whole organization?
I'm against a global hard number: it pushes people to write tests with no asserts and getter tests. Instead I choose a "coverage must not drop for changed code" rule, a higher threshold for critical modules, and mutation score.
83
The shared staging environment for microservices is always broken. How do you redesign the integration test environment?
Instead of one shared staging, I make short-lived (ephemeral) environments per PR and make contract tests the main layer of defense. I keep the shared staging only for a limited set of smoke and e2e flows before a release.
84
How do you wire contract tests into the CI/CD process so that a provider can't deploy a version that breaks a consumer?
Contracts are stored in the broker with the consumer version and environment; the provider verifies them in every build and writes the result to the broker; and in the deploy pipeline each side asks can-i-deploy "am I compatible with my partners in this environment?". After a deploy, the environment is recorded in the broker.
85
What do you think of the "testing in production" approach, and how do you organize it safely?
No test environment fully reproduces prod traffic, data and configuration, so checking in prod doesn't replace the earlier tests, it continues them. I organize it through feature flags, canaries, synthetic monitoring and shadow traffic, with automatic rollback.
86
What infrastructure problems does using Testcontainers in CI cause, and how do you solve them at the organization level?
CI runners need access to Docker (Docker-in-Docker or a socket mount, and both have a security cost), pulling images every time is slow and hits the Docker Hub limit, and parallel jobs compete for resources. The solution is an internal registry mirror, pre-warmed images, and a remote container runtime if needed.
87
In a monorepo, a full 40-minute test suite runs on every PR. How do you design running only the tests relevant to the change?
Based on the build graph, I find the "affected" modules and test only them and the modules that depend on them (at the Gradle/Bazel level), then as a safety measure I run the full suite on main or in the merge queue. Test impact analysis is a trade-off between speed and the risk of skipping something.
88
In an event-driven system (Kafka, several consumer services), how do you test end-to-end correctness?
I test each service in isolation at its own boundary, protect the message format with Schema Registry compatibility and message contracts, and at the e2e level I follow a few main flows by correlation ID and wait for them to reach the "eventual" state. You can't try every combination in e2e.
89
What metrics do you use to watch the health of the test suite at the organization level?
The main four: PR feedback time (p50/p90), the share and number of flaky tests, incidents that reached prod because of regressions (escaped defects), and the share of bugs that tests caught. Coverage is supporting context, not a goal.
90
How do you add load tests to the pipeline to automatically catch performance regressions before a release?
Not on every PR; I run them on main or nightly in a stable, isolated environment with a fixed scenario (Gatling, k6 or JMeter), compare the result with the previous baseline, and alert if p95/p99 or throughput crosses a threshold. Small hot spots get JMH micro-benchmarks, separately.
91
What is the difference between fault injection tests and chaos engineering, and when does it make sense to start a chaos practice in an organization?
Fault injection tests are deterministic tests in CI that check a specific hypothesis (for example, if the database drops, the service returns 503). Chaos engineering is system-level experiments in a real or prod-like environment. It's best to start chaos once observability, automatic recovery, and who does what during an incident are in place.
92
When you split a service out of a monolith, how do tests guarantee that behavior hasn't changed?
Before the split I write tests at the monolith's boundary that pin down behavior (golden master, API-level tests), then I run the new service in shadow mode and compare the old and new responses on prod requests. Only when the differences are near zero do I move traffic over step by step.
93
You're being asked to copy prod data to test and staging environments. How do you decide?
I'm against a direct copy of prod: the risk from personal data, payment details and legal requirements (Uzbekistan's personal data law, GDPR) is high. Instead I provide synthetic data generation, or, if needed, a subset that has gone through a pipeline with irreversible anonymization.
94
How do you automatically detect that backward compatibility of a public API has been broken?
I generate the OpenAPI specification from the code, diff it against the version on main in every PR, and stop the build on breaking changes (removing a field, adding a required parameter, changing a type). I add contract tests that work with old client versions, and serialization snapshot tests.
95
Between a separate QA team and a "developers write the tests" model, how do you structure the organization?
The owner of automated tests is the team that wrote the code, otherwise feedback is delayed and the tests drift away from the code. QA engineers focus on test strategy, risk analysis, exploratory testing and test infrastructure. They aren't "manual checkers", they're quality coaches.
96
How do you test a distributed business process built with sagas (order → payment → subscription → author share)?
I test each step and its compensation separately, unit test the saga orchestrator as a state machine with all its transitions and errors, and at the integration level I inject failures on purpose and check that the system reaches a consistent final state. The most important test is the failure halfway through.
97
The platform team proposes building a shared test library for all services. How do you evaluate it?
It's useful for repeated infrastructure code (Testcontainers setup, an auth token generator, Kafka test helpers), but putting domain fixtures and service-specific builders in a shared library ties the services to each other. The library should be small, versioned and optional.
98
When is property-based testing more useful than ordinary example-based tests, and how do you introduce it into a project?
Where the input space is large and you can state the invariant precisely: money calculation, serialization round trips, parsers, state machines, two implementations that must give the same result. In Java, jqwik runs such tests on the JUnit 5 platform and shrinks a failing case down to the smallest example.
99
How do you use tests to protect architecture rules (layers, module boundaries) from eroding over time?
With a tool like ArchUnit I write the architecture rules as ordinary JUnit tests: controllers must not touch the repository directly, the domain package must not depend on Spring, modules talk only through their public API. They run on every build and catch violations that slipped past review.
100
In a zero-downtime deploy, how do you use tests to check that database schema changes (expand/contract) are safe?
I check every migration on the assumption that two versions run at the same time: I run the tests of the old code version against the new schema, and I measure the migration for locks and time on data close to the real volume. For breaking changes (dropping or renaming a column) I add linter rules.
Sign up — studied questions get marked and your progress is saved.