Created
October 15, 2014 06:59
-
-
Save khajavi/9707bbd94e5fefcfce62 to your computer and use it in GitHub Desktop.
Mocking private memebers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Calculator { | |
private DAO dao; | |
public int add() { | |
dao = new DAO(); | |
return dao.getA() + dao.getB(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DAO { | |
public int getA() { | |
return 1; | |
} | |
public int getB() { | |
return 2; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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