1. Which annotation selects the dev profile for a test class?
@SpringJUnitWebConfig(AppConfig.class)
// Add annotation here
class GreetingTest {
...
}
Why:@ActiveProfiles is placed on the test class. It tells the test context which profiles to activate when the application context is loaded.
2. What does @ActiveProfiles do in a Spring test class?
Why:@ActiveProfiles sets the active profiles for the test context. Beans whose @Profile matches are registered, and the others are left out.
3. The controller returns the value of greeter.get() for a GET request to /. What is the response body when this test runs?
interface Greeter { String get(); }
@Service
@Profile("default")
class LocalGreeter implements Greeter {
public String get() { return "local"; }
}
@Service
@Profile("dev")
class DevGreeter implements Greeter {
public String get() { return "dev"; }
}
@Controller
class HomeController {
@Autowired Greeter greeter;
@GetMapping("/")
@ResponseBody
String handle() { return greeter.get(); }
}
@SpringJUnitWebConfig(AppConfig.class)
@ActiveProfiles("dev")
class HomeTest { ... }
Why: The dev profile is active in the test, so only the bean marked with @Profile("dev") is registered and injected. The default profile bean is not used.
4. The test class below has no @ActiveProfiles. What does greeter.get() return?
@Service
@Profile("default")
class LocalGreeter implements Greeter {
public String get() { return "local"; }
}
@Service
@Profile("dev")
class DevGreeter implements Greeter {
public String get() { return "dev"; }
}
@SpringJUnitWebConfig(AppConfig.class)
class GreeterTest {
@Autowired Greeter greeter;
}
Why: When no profile is activated, Spring uses the default profile. So the bean marked with @Profile("default") is registered and the dev bean is not.
5. Which annotation activates both dev and cloud profiles in a test class?
Why: The profile names are given as a String array, so more than one name must be wrapped in curly braces.
6. A test class activates the dev profile. It also autowires a bean that exists only for the prod profile. What happens?
Why: A bean marked with @Profile("prod") is registered only when prod is active. Without it, the dependency cannot be satisfied, so the context fails to load.