Reputation: 773
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 ?
Upvotes: 1
Views: 12413
Reputation: 5451
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();
}
}
Upvotes: 4
Reputation: 38328
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:
Upvotes: 0