We help IT Professionals succeed at work.

mockito example setter

hi,
I was writing below example
https://www.youtube.com/watch?v=ShO_Z64sGwI&list=PLZM-6wiKGRfGmXzuR8uX3UsE8g91K6Vp1&index=5

package com.gp.mockito;

import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;
import static org.mockito.Mockito.*;

public class CalculatorServiceTest {

	CalculatorService calService;
	
	@Before
	public void setup(){
		ICalculator cal_mock = mock(ICalculator.class);
		when(cal_mock.add(2, 4)).thenReturn(6);
		calService=new CalculatorService();
		//calService.setCal(cal_mock);
		
		
	}
	@Test
	public void testAddNumbers(){
		Assert.assertEquals(6, calService.addTwoNumbers(2,4));
	}
}

Open in new window

package com.gp.mockito;

public class CalculatorService {
ICalculator cal;
public ICalculator getCal() {
	return cal;
}
public void setCal(ICalculator cal) {
	this.cal = cal;
}
public int addTwoNumbers(int x, int y){
	return cal.add(x, y);
}
}

Open in new window

package com.gp.mockito;

public interface ICalculator {
public int add(int x,int y);
}

Open in new window

why we need setter for calservice implementation class.

why are they setting interface mock object to the calservice object

observerd one example here
https://www.youtube.com/watch?v=DyuWgBHfxNQ

i do not see any setter here though?
Comment
Watch Question

Top Expert 2015
Commented:
The class under test is calculatorservice.

The ICalculator is a dependency of this class.

If you mock the dependency you need to tell the class under test to make use of the mocked dependency and not the real one. One way of doing it is via a setter method or a constructor or just use dependency injection.

Author

Commented:
here they are using setter method?
more like spring concept?

Author

Commented:
If you mock the dependency you need to tell the class under test to make use of the mocked dependency and not the real one. One way of doing it is via a setter method or a constructor or just use dependency injection
if i implement that interface in the class then there is no need of this setter here?

package com.gp.mockito;

public class CalculatorService implements ICalculator {
and then implements interface method here

public int add(int x, int y) {
      // TODO Auto-generated method stub
      return 0;
}

Author

Commented:
If you mock the dependency you need to tell the class under test to make use of the mocked dependency and not the real one. One way of doing it is via a setter method or a constructor or just use dependency injection.
sounds more like spring concept