问题
I want to mock a private method which has been called inside another method.
Following is the sample code, I have written.
Java code:
package org.mockprivatemethods;
public class AccountDeposit {
// Instantiation of AccountDetails using some DI
AccountDetails accountDetails;
public long deposit(long accountNum, long amountDeposited){
long amount = 0;
try{
amount = accountDetails.getAmount(accountNum);
updateAccount(accountNum, amountDeposited);
amount= amount + amountDeposited;
} catch(Exception e){
// log exception
}
return amount;
}
private void updateAccount(long accountNum, long amountDeposited) throws Exception {
// some database operation to update amount in the account
}
// for testing private methods
private int sum(int num1, int num2){
return num1+num2;
}
}
class AccountDetails{
public long getAmount(long accountNum) throws Exception{
// some database operation returning amount in the account
long amount = 10000L;
return amount;
}
}
Testclass:
package org.mockprivatemethods;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
@RunWith(PowerMockRunner.class)
public class TestAccountDeposit {
@InjectMocks
AccountDeposit accountDeposit;
@Mock
AccountDetails accountDetailsMocks;
@Test
public void testDposit() throws Exception{
long amount = 200;
when(accountDetailsMocks.getAmount(Mockito.anyLong()))
.thenReturn(amount);
// need to mock private method updateAccount
// just like we tested the private method "sum()" using Whitebox
// How to mock this private method updateAccount
long totalAmount = accountDeposit.deposit(12345678L, 50);
assertTrue("Amount in Account(200+50): "+totalAmount , 250==totalAmount);
}
@Test
public void testSum(){
try {
int amount = Whitebox.invokeMethod(accountDeposit, "sum", 20, 30);
assertTrue("Sum of (20,30): "+amount, 50==amount);
} catch (Exception e) {
Assert.fail("testSum() failed with following error: "+e);
}
}
}
We can test the private methods using Whitebox.invokeMethod()
. My question is: Is there any to way mock the private method using Whitebox. Can we write something similar to below code to mock the updateAccount() as I do not want any database operation to be performed while testing the Deposit() method?strong text
when(accountDetailsMocks.getAmount(Mockito.anyLong()))
.thenReturn(amount);
Any help is appreciated! Thanks!
来源:https://stackoverflow.com/questions/51150117/how-to-mock-private-methods-using-whiteboxorg-powermock-reflect