title: Mock object method call using Spring Boot and Mockito
body: <p>I am trying to write a test for this Java SpringBoot's class: </p>
  
  <blockquote>
    <p><a href="https://github.com/callistaenterprise/blog-microservices/blob/master/microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/service/ProductCompositeIntegration.java" rel="noreferrer">https://github.com/callistaenterprise/blog-microservices/blob/master/microservices/composite/product-composite-service/src/main/java/se/callista/microservices/composite/product/service/ProductCompositeIntegration.java</a></p>
  </blockquote>
  
  <p>Specifically, I am trying to "mock" this method call:</p>
  
  <pre><code>URI uri = util.getServiceUrl("product");
  </code></pre>
  
  <p>I figured out I should "mock" the <code>ServiceUtils</code> object in order to do this. I tried this using the <code>@Mock</code> and <code>@InjectMocks</code> annotations:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @SpringApplicationConfiguration(classes = ProductCompositeServiceApplication.class)
  public class ProductCompositeIntegrationTest {
  
      @InjectMocks
      @Autowired
      private ProductCompositeIntegration productIntegration;
  
      @Autowired
      private RestTemplate restTemplate;
  
      @Mock
      private ServiceUtils util;
  
      private MockRestServiceServer mockServer;
  
      @Before
      public void setUp() {
          MockitoAnnotations.initMocks(this);
          mockServer = MockRestServiceServer.createServer(restTemplate);
      }
  
      @Test
      public void myTest() {
          Mockito.when(util.getServiceUrl("product")).thenReturn(URI.create("http://localhost:8080/test"));
          ResponseEntity&lt;Iterable&lt;Product&gt;&gt; products = productIntegration.getAllProducts();
      }
  }
  </code></pre>
  
  <p>But this way it still calls the original <code>ServiceUtils</code> object, and not the "mocked" one. Also tried without the <code>@Autowired</code> annotation at the <code>ProductCompositeIntegration</code>, but this results in a <code>NullPointerException</code>.</p>
  
  <p>What am I doing wrong?</p>
  
  <hr>
  
  <p>My main class looks like this:</p>
  
  <pre><code>@SpringBootApplication
  @EnableCircuitBreaker
  @EnableDiscoveryClient
  public class ProductCompositeServiceApplication {
      public static void main(String[] args) {
          SpringApplication.run(ProductCompositeServiceApplication.class, args);
      }
  }
  </code></pre>
  
  <p>The <code>ServiceUtils</code> object that I am trying to mock is specified in a class, annotated with Spring's <code>@Component</code> annotation to inject it into the other classes using <code>@Autowired</code>.</p>