Junit Test (Mockito, PowerMock) a class with void method and private value - junit

some sample code like:
(I just added some more details)
public class A {
#Autowired
private Data data;
#RequestMapping(value="/Boo", method = RequestMethod.GET)
public void Boo(){
data.someMethod();
}
}
I want to test the someMethod() is run or not.
I have tried #First answer but got some error message like below:
java.lang.AbstractMethodError: org.powermock.api.mockito.internal.exceptions.StackTraceCleanerProvider$1.isIn(Ljava/lang/StackTraceElement;)Z
at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.filter(StackTraceFilter.java:33)
at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.filter(ConditionalStackTraceFilter.java:23)
at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:44)

#RunWith(MockitoJUnitRunner.class)
public class ATest {
#InjectMocks
private A a;
#Spy
private Data data;
#Test
public void test() {
// execute
this.a.Boo();
// verify
Mockito.verify(this.data).someMethod();
}
}

Related

Getting NullPointerException while accessing the SuperClass method call using powermock

Getting NullPointerException while accessing the SuperClass method call using powermock
While running the below mentioned testclass getting NullPointerException error at above mentioned line in switch(super.getType())
public class CommandParamInput extends AbstractCommandParam {
public CommandParamInput(
final ParameterFeedType commandParameterSourceToSet,
final Object definedValueToSet) {
this.commandParameterSource = commandParameterSourceToSet;
this.definedValue = definedValueToSet;
}
public void evaluateValue(final FDPRequest fdpRequest)
throws EvaluationFailedException {
switch (super.getType()) {
case ARRAY:
evaluateComplexValue(fdpRequest);
break;
}
}
}
While running the below mentioned testclass getting NullPointerException error at above mentioned line in switch(super.getType())
#RunWith(PowerMockRunner.class)
#PrepareForTest({AbstractCommandParam.class,CommandParameterType.class,ParameterFeedType.class,LoggerUtil.class,Logger.class})
public class CommandParamInputTest {
private Logger loggerMock;
private FDPRequest instFDPRequest;
private FDPResponse instFDPResponse;
private FDPCacheable instFDPCacheable;
private AbstractCommandParam cmdParam;
private CommandParamInput spy;
#Mock
AbstractCommandParam absCommandParam;
#Mock
CommandParameterType cmdParameterType;
#Mock
ParameterFeedType parameterFeedType;
#InjectMocks
private CommandParamInput commandParamInput;
#Before
public void init() {
FDPRequestImpl fdoRequestImpl = new FDPRequestImpl();
fdoRequestImpl.setCircle(new FDPCircle(new Long(10),"10","test"));
fdoRequestImpl.setChannel(ChannelType.USSD);
instFDPRequest = fdoRequestImpl;
spy = PowerMockito.spy(new CommandParamInput(parameterFeedType.AUX_REQUEST_PARAM, instFDPCacheable));
}
#Test
public void testEvaluateValue()throws ExecutionFailedException,
EvaluationFailedException, FileNotFoundException, RuleException{
mockCommonObjects();
commonMockExternalCall();
absCommandParam = new CommandParamInput(parameterFeedType.AUX_REQUEST_PARAM, instFDPCacheable);
absCommandParam.setType(cmdParameterType.PARAM_IDENTIFIER);
PowerMockito.doReturn(cmdParameterType.PARAM_IDENTIFIER).when(spy).getType();
// when(absCommandParam.getType()).thenReturn(cmdParameterType.PARAM_IDENTIFIER);
PowerMockito.suppress(PowerMockito.methods(AbstractCommandParam.class, "getType"));
commandParamInput.evaluateValue(instFDPRequest);
}
}

Mocking an injected object in a method return and UnsupportedOperationException method

I have a class that returns an injected object using Mockito. Everytime I test it, it returns a bull. How would I properly test it to return the correct object?
My class to test:
#Component
public class CarImpl {
#Inject
private Engine v6EngineImpl;
public Engine getEngine() {
return v6EngineImpl;
}
public Exhaust getExhaust() {
throw new UnsupportedOperationException("unsupported");
}
}
Tests:
#RunWith(MockitoJUnitRunner.class)
public class CarTest {
#InjectMocks
private CarImpl carImpl;
#Mock
private Engine v6EngineImpl;
#Test
public void testGetEngine(){
Engine v6EngineImpl = mock(V6EngineImpl.class);
Engine engine = carImpl.getEngine();
// always returns a bull no matter what, how to mock inject.
//return object correctly?
Assert.assertNotNull(engine);
}
#Test
public void testGetExhaust() {
// how to test thrown exception?
}
}
Thanks, I am not too familiar thanks
Try this:
#RunWith(MockitoJUnitRunner.class)
public class CarTest {
#InjectMocks
private CarImpl carImpl;
#Mock
private Engine v6EngineImpl;
#Test
public void testGetEngine(){
Engine engine = carImpl.getEngine();
//engine is the mock injected to CarImpl
Assert.assertNotNull(engine);
Assert.assertSame(engine,v6EngineImpl);
}
#Test(expected=UnsupportedOperationException.class)
public void testGetExhaust() {
carImpl.getExhaust();
}
}

How to mock a void method with no arguments?

For Example:
Class A{
string s = null;
public void method(){
s="Sample String";
}
}
I have a void method with similar scenario. How can I test such void method?
With void methods you should test the interaction with its dependent objects within the void method. I think a void method with no argument is rarely useful to test (but if you have a valid use case, please add it to your question). I provided you a simple example for a method with an argument but void as a return type:
public class A {
private DatabaseService db;
private PaymentService payment;
// constructor
public void doFoo() {
if(n < 2) {
db.updateDatabase();
} else {
payment.payBill();
}
}
}
And the unit test for this can look like the following
#RunWith(MockitoJUnitRunner.class)
public class ATest {
#Mock
DatabaseService db;
#Mock
PaymentService payment;
#Test
public void testDoFooWithNGreaterTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(3);
verify(payment).payBill(); // verify that payment was called
}
#Test
public void testDoFooWithNLessThanTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(1);
verify(db).updateDatabase(); // verify that db was called
}
}

How to write JUnit Test case

I am learning Junit testing on spring boot Application. my account controller method is depend on service class method. For that I used Mockito. I tried simple But here I am not getting how to write test case for following method? How I can use mockito.
can any one please help me for writing this test case?
AccountController
#RestController
#RequestMapping("/spacestudy/$ {InstituteIdentifier}/admin/account")
public class AccountController {
#Autowired
AccountService accService;
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(#RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
#RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
#RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
#RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
}
AccountService
public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId)throws Exception{
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, investigator);
if (StringUtils.isNotEmpty(sClientAcctId)) {
query.where(account.sClientAcctId.equalsIgnoreCase(sClientAcctId));
}
// code.......
return query.fetch();
}
AccountControllerTest
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
//????
//????
}
}
It will be something like this:
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
when(accountService.populateGridViews("foo","bar")).thenReturn(Arrays.asList(new Tuple("bazz"));
mockMvc.perform(get("/spacestudy/STACKOVERFLOW/admin/account/foo/bar"))
.andExpect(status().isOk())
.andExpect(jsonPath("someField").value("bazz"));
}
}
So basically you are replacing your service with mock and saying what it should return. In your particular case I don't see any reasons for unit testing this class, since it doesn't have any logic inside. But if you would have something like:
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(...) throws Exception {
List<Tuple> result = accService.populateGridViews(...);
if(result==null){
return ResponseEntity.notFound();
}
return ResponseEntity.ok(result);
}
Then it would make more sense to test this class e.g.
1st test - mock your accService to return null and verify that response status is 404
2nd test - mock your accService to return not null and verify that response status is 200

Performing a custom action when a given mocked void method is called

I would like to be able for Mockito to perform a custom action when a given void method is called.
Say I have the following code:
#Autowired
private ProfileService profileService;
#Autowired
private ProfileDao profileDao;
private List<Profile> profiles;
#Before
public void setup() {
Mockito.when(profileDao.findAll()).thenReturn(profiles);
Mockito.when(profileDao.persist(any(Profile.class))).thenAddProfileToAboveList...
}
#Configuration
public static class testConfiguration {
#Bean
public ProfileDao ProfileDao() {
return mock(ProfileDao.class);
}
}
Say I want to add a Profile instance to the profiles list. Can Mockito do that? If so how?
Use Mockito.doAnswer.
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
// make the changes you need here
}})
.when(mock).someMethod();