1

I am doing some tests for the class Export I need to mock a method so I made a mockito (I am new to Mockito)

public Class ExportServiceImpl implements ExportService{

   @Autowired
   Service service

   public void export(){

      String exportString = service.getPath();
      domoreStuff() ....

  }    

And

  public Class ServiceImpl implements Service(){

      public String getPath(){
          return "thePath";
      }
  }   

I need to mock the getPath() method so I did in the TestNG

 public class ExportTestNG(){

    public textExport(){

     Service serviceMock = Mockito.mock(Service.class);
     Mockito.when(serviceMock.getData()).thenReturn("theNewPath");
     System.out.println("serviceMock.getData() : " + serviceMock.getData()); // prints "theNewPath", OK

     exportService.export();  // the getData() is not the mockito one

    }
 }

I may have not correclt mockito and I may not have understood how it works. Any idea ?

Makoto
  • 765
  • 2
  • 17
  • 45
  • possible duplicate of [Injecting Mockito mocks into a Spring bean](http://stackoverflow.com/questions/2457239/injecting-mockito-mocks-into-a-spring-bean) – Mike B Apr 30 '14 at 16:34

2 Answers2

4

You can use Mockito to inject the mocks for you and avoid having to add setter methods.

@RunWith(MockitoJUnitRunner.class)
public class ExportTestNG(){

    @InjectMocks
    private ExportServiceImpl exportService;

    @Mock
    private Service serviceMock;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    public textExport(){                            
        Mockito.when(serviceMock.getData()).thenReturn("theNewPath");
        exportService.export(); 
    }
}
Mike B
  • 5,390
  • 2
  • 23
  • 45
0

You need to wire the mock service into the exportService object. If you have a setter for the service member variable then do this:

exportService.setService(serviceMock);// add this line.
exportService.export();

If you don't have a setter you will need to perform the wiring before calling export. Options for this include:

  • Set the value of the service member variable using reflection.
  • Write a test-only version of the Service and use a test-only version of the spring configuration xml files.
  • Something else (that I have never done and thus don't know about).
DwB
  • 37,124
  • 11
  • 56
  • 82
  • "Write a test-only version of the Service " NO! Then you're testing code that's never used, and not testing the code that is used. Waste of time. – Don Branson Apr 30 '14 at 17:06
  • 2
    a test only version of the service is to support the testing of the exportService, just like using a Mocking library. The code being tested is not the test only version of the service but the class that is using the test only version of the service. – DwB Apr 30 '14 at 18:16
  • Ah, a mock service then. That's normally what it would be called. – Don Branson May 01 '14 at 20:39