Question

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 ?

Was it helpful?

Solution 2

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).

OTHER TIPS

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(); 
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top