Skip to content

Instantly share code, notes, and snippets.

@khajavi
Created October 15, 2014 06:59
Show Gist options
  • Save khajavi/9707bbd94e5fefcfce62 to your computer and use it in GitHub Desktop.
Save khajavi/9707bbd94e5fefcfce62 to your computer and use it in GitHub Desktop.
Mocking private memebers
public class Calculator {
private DAO dao;
public int add() {
dao = new DAO();
return dao.getA() + dao.getB();
}
}
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Calculator.class })
public class CalculatorTest {
@Mock
private DAO mydao;
@InjectMocks Calculator cal;
@Test
public void testAdd() throws Exception {
when(mydao.getA()).thenReturn(4);
when(mydao.getB()).thenReturn(5);
whenNew(DAO.class).withNoArguments().thenReturn(mydao);
assertEquals(9, cal.add());
}
}
public class DAO {
public int getA() {
return 1;
}
public int getB() {
return 2;
}
}
<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment