{"record":{"id":"c775a968467b8a86","repo":"karatelabs/karate","slug":"mock-background-failed-at-line-line-message","errorCode":null,"errorMessage":"mock background failed at line <line>: <message>","messagePattern":"mock background failed at line <line>: <message>","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"karate-core/src/main/java/io/karatelabs/core/MockHandler.java","lineNumber":289,"sourceCode":"            currentRequest != null ? markRequestDerived(runtime, currentRequest.getMultiParts()) : null);\n        engine.put(\"requestCookies\", (JsLazy) () ->\n            currentRequest != null ? markRequestDerived(runtime, currentRequest.getCookies()) : null);\n\n        // Put args into globals if provided\n        if (args != null) {\n            globals.putAll(args);\n            for (var entry : args.entrySet()) {\n                engine.put(entry.getKey(), entry.getValue());\n            }\n        }\n\n        // Execute background once on initialization using StepExecutor\n        StepExecutor executor = new StepExecutor(runtime);\n        if (feature.isBackgroundPresent()) {\n            for (Step step : feature.getBackground().getSteps()) {\n                StepResult result = executor.execute(step);\n                if (result.isFailed()) {\n                    throw new RuntimeException(\"mock background failed at line \" + step.getLine() + \": \" +\n                        result.getError().getMessage(), result.getError());\n                }\n            }\n            // Save background variables to globals\n            saveGlobals(engine);\n\n            // Transfer configure settings to MockConfig\n            KarateConfig karateConfig = runtime.getConfig();\n            if (karateConfig.isCorsEnabled()) {\n                config.setCorsEnabled(true);\n            }\n            Object responseHeaders = karateConfig.getResponseHeaders();\n            if (responseHeaders instanceof Map) {\n                config.setResponseHeaders((Map<String, Object>) responseHeaders);\n            }\n            Object beforeScenario = karateConfig.getBeforeScenario();\n            if (beforeScenario instanceof JavaCallable callable) {\n                config.setBeforeScenario(callable);","sourceCodeStart":271,"sourceCodeEnd":307,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/core/MockHandler.java#L271-L307","documentation":"MockHandler.initRuntime executes the feature's Background section once at mock-server initialization and, if any Background step fails, wraps the step's failure in a RuntimeException. This fails fast at server startup because a broken Background would leave mock state incomplete for every request.","triggerScenarios":"Calling MockServer.start() with a feature whose Background steps fail — e.g. a failing match assertion, a JS error, or a missing variable defined via call in the Background.","commonSituations":"Refactoring a shared feature reused as a mock so its Background now depends on an undefined variable; a broken JSON/cucumber expression in a Background step; environment-specific config not available when the mock boots.","solutions":["Fix the failing Background step in the mock feature — run it as a normal feature test to see the full failure first","Check result.getError().getMessage() embedded in the exception (and its cause) for the underlying step error","Remove heavy logic from Background and move optional setup into Scenario outlines or callonce","Validate the feature standalone (Runner / karate runner) before wiring it into MockServer"],"exampleFix":"// before\nBackground:\n* def user = call read('users.feature')\n* match user.id == '#number'\n// after (guard the step and fail with a clear message)\nBackground:\n* def user = call read('users.feature')\n* assert user != null : 'users.feature did not return a user'","handlingStrategy":"validation","validationCode":"StepResult r = new StepExecutor(runtime).execute(step);\nif (r.isFailed()) throw new IllegalStateException(\"background step line \" + step.getLine() + \" failed: \" + r.getError().getMessage());","typeGuard":null,"tryCatchPattern":"try { server = MockServer.builder().feature(path).http(port).build().start(); } catch (RuntimeException e) { if (e.getMessage().startsWith(\"mock background failed\")) { log.error(\"Mock feature Background invalid: {}\", e.getCause(), e); } throw e; }","preventionTips":["Run the mock feature as a normal Karate feature in CI before using it as a mock","Keep Background minimal — only variable setup, no brittle match assertions","Read the wrapped cause (result.getError()) for the real step failure"],"tags":["mock-server","background","feature","startup"],"backgroundTag":"invalid-state-transition","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}