title: Spring test service class mocking utility class- Junit and Mockito
body: <p>I want to write test cases for service layer of spring framework using <code>Junit + Mockito.</code></p>
  
  <p>How to call the actual service layer method using my <code>ServiceTest</code> class, If i mock the <code>ServiceTest</code> class then it's object wont execute the actual service method code because it wont get the object to call it's methods and if I try with the Spy still it was not working, <a href="https://github.com/skprasadu/spring-mvc-examples" rel="nofollow noreferrer">I tried this example</a>
  still I  not able to execute the test cases.</p>
  
  <p><strong>MyService.java</strong></p>
  
  <pre><code>@Service
   public class MyService{
  
      @Autowired
      Utility utility;
  
      public String showResult(){
  
      String result = utility.getName();
  
      return result;
      }
      }
  </code></pre>
  
  <p><strong>MyServiceTest.java</strong></p>
  
  <pre><code>    @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(loader=AnnotationConfigWebContextLoader.class)
      @WebAppConfiguration
      public class MyServiceTest {
  
          @Autowired
          MyService myService;
  
  
          @Autowired
          Utility utility; 
  
  
  
  
          @Test
          public void testShowResult() throws Exception {
  
              assertEquals("Test",myService.showResult());
  
          }
  
          @Configuration
          static class MykServiceTestContextConfiguration {
  
              @Bean
              public MyService myService() {
                  return new MyService();
              }           
  
              @Bean
              public Utility utility() {
                  return Mockito.mock(Utility.class);
              }
          }
  
      }
  </code></pre>