title: Can we mock a method in service while testing the service itself?
body: <p>I am working on a project where I am using MyBatis annotations as persistence framework. Therefore, I have to create an interface for the 'mapper' and compose the mapper in the service like :</p>
  
  <pre><code>class XYZServiceImpl{
  
      public XYZMapper getXYZMapper(){
          return SessionUtil.getSqlSession().getMapper(XYZMapper.class)
      }
  
  }
  </code></pre>
  
  <p>Now while unit testing the service with Mockito, I am trying to inject a mock for the mapper. But since I am injecting mock in an instance of XYZService, how can mock a method of the service itself, in this case getXYZMapper() is what I am trying to stub. Although I have got a solution of creating the instance XYZMapper in the service and not call on demand like the above code does something like : </p>
  
  <pre><code>  Class XYZServiceImpl{
  
          XYZMapper mapper;
  
          public void useXYZMapper(){
              mapper = SessionUtil.getSqlSession().getMapper(XYZMapper.class);
          }
  
      }
  </code></pre>
  
  <p>But that would bring a lot of code changes (ofcourse I can refactor) but is there a way to achieve without having to make code changes?</p>
  
  <p>Also what would be a 'purist' way to have a mapper instance in the class is it the method 1 that is better than method 2 in terms of performance?</p>
  
  <p>EDIT : Here XYZMapper is an interface. Something like :</p>
  
  <pre><code>public interface XYZMapper{
      @Select("SELECT * FROM someclass WHERE id = #{id}")
      public SomeClass getSomeClass(int id);
  
  }
  </code></pre>
  
  <p>EDIT : I am facing a similar situation but with a variance that I have a service that I do want to test like XYZServiceImpl. Now it has a method getXYZDetails() which has a lot of business logic handled within the service. Now if getXYZDetails looks like the following :</p>
  
  <pre><code>public XYZDetails getXYZDetails(int id){
  
    XYZDetails details = new XYZDetails();
  
    details.set1Details(fetchSet1Details(id));
  
    //Perform some business logic
  
    details.set2Details(fetchSet2Details(id));
  
    if(details.set2Details() != null){
      for(int i = 0; i &lt; details.set2Details().size(); i++){
        flushTheseDetails(i);
      }
    }
    .
    .
  
  }
  </code></pre>
  
  <p>Kindly notice that fetchSet1Details(), fetchSet2Details(), flushTheseDetails are public service, public and private service respectively.</p>
  
  <p>I want to know of a method that can mock/stub these methods while testing getXYZDetails() thus enabling me to </p>