JUnit, Spring, Spring Boot

Create Spring service used only in test environment

Create Spring service used only in test environment

In my project, we use three different environments for running the application.

  • Production
  • SIT (system integration)
  • Local development

In the production environment thee is a third party system, that authenticates the user and automatically adds a header value to the request.

I wanted to implement a feature, which always requires the authentication information. So I needed to add mocked information into the REST request header in SIT and Local development environment.

I used a Service to process the request, and created additional subclasses for Local development and SIT environments. The subclasses must not be annotated as service. Otherwise you get exception at startup, marking that your service class in not unique.

The configuration of my local development environment looks like this:

public class BackendConfigurationLocalDev extends BackendConfiguration {

private DaoConfiguration daoConfiguration;

@Bean(value = “crbService”)
public CrbService getCrbService() {
return new CrbServiceLocalDev();

In order to add header values to the REST request, I implemented a HttpServletRequestWrapper class.

My service for local development looks like this:

public class CrbServiceLocalDev extends CrbService {

// Logger instance
private static final Logger log = LoggerFactory.getLogger(CrbServiceLocalDev.class);

private static final String HARDCODED_CRB_USER_STATUS_HEADER_VALUE = “{\”key\”:\”value\”}”;

public CrbUserInfo createCrbUserInfo(HttpServletRequest request) {
log.warn(“Entering CrbServiceLocalDev.createCrbUserInfo(). Must be used only for local development”);

HttpServletRequestWrapper wrapper = new LocalDevHttpServletRequestWrapper(request);
return super.createCrbUserInfo(wrapper);

private class LocalDevHttpServletRequestWrapper extends HttpServletRequestWrapper {

public LocalDevHttpServletRequestWrapper(HttpServletRequest request) {

public String getHeader(String name) {

if (StringUtils.isBlank(name)) {
return super.getHeader(name);

final String value = getRequest().getParameter(name);
if (!StringUtils.isBlank(value)) {
return value;

if (MobileAppCrbUserStatus.HEADER_PARAM_X_CRB_USERSTATUS.equals(name)) {
log.warn(“Hardcoded userstatus header value is returned: {}”, HARDCODED_CRB_USER_STATUS_HEADER_VALUE);

return super.getHeader(name);




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s