title: How to override @Primary bean in spring boot Junit test cases
body: <p>I have a spring boot application which has,</p>
  <p>an interface : <strong>EmailService</strong>
  and it's implementation : <strong>EmailServiceImpl</strong> - This class is annotated with <strong>@Primary</strong></p>
  <pre><code>@Scope(value = &quot;prototype&quot;)
  @Service
  @Primary
  public class EmailServiceImpl implements EmailService {
  
      public void validateEmail(String email){
          // validation check
      }
  }
  </code></pre>
  <p>I have another class ResourceService in which the above implementation is autowired.</p>
  <pre><code>@Scope(value = &quot;prototype&quot;)
  @Service
  public class ResourceService implements ResourceServiceInterface {
      
      @Autowired
      EmailService emailService;
  
      public boolean checkResource(String email, Long resourceId){
          emailService.validateEmail(email);
          // Code to check the resource
      }
  }
  </code></pre>
  <p>I am trying to write junit test case for above checkResource() method in which I want to bypass the emailService.validateEmail(email) method.</p>
  <pre><code>@ActiveProfiles(&quot;test&quot;)
  @RunWith(SpringJUnit4ClassRunner.class)
  @WebAppConfiguration
  @ContextConfiguration(classes = Application.class, loader = SpringApplicationContextLoader.class)
  public class JunitClass {
  
      @Autowired
      private EmailService emailService;
  
      @Autowired
      private ResourceServiceInterface resource;
  
      @Test
      public void testMethod() {
          Mockito.doNothing().when(emailService).validateEmail(Mockito.anyString());
          boolean validResource = resource.checkResource(&quot;email@gmail.com&quot;, 1234L);
          assertEquals(validResource, true);
      }
  }
  </code></pre>
  <p>and the configuration class is,</p>
  <pre><code>@Profile(&quot;test&quot;)
  @Configuration
  public class ServConf {
      
      @Bean
      @Primary
      public EmailService getEmailService() {
          return Mockito.mock(EmailServiceImpl.class);
      }
  }
  </code></pre>
  <p>of course this code does not work because Spring detects two beans annotated with Primary.
  <strong>What is the work around to bypass the emailService.validateEmail(email) call during the junit test case run?</strong>
  If I remove the @Primary from EmailServiceImpl, it will work for sure. But I am not supposed to modify the original code.</p>