Powermock + Mockito not working - java

Trying to use Powermock to mock out a static method on SystemTray. Not sure why this isn't working. I've checked the match of Powermock -> Mockito versions, and I think I've followed all the steps for adding the right annotations, and using the correct PowerMock methods to setup the static one.
The static method on SystemTray seems to be called without the stubbed functionality set by the when().
I am mixing Powermock and Mockito calls here, but according to the docs that is correct.
package CommissionChecker;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.test.util.ReflectionTestUtils;
import java.awt.*;
import java.io.IOException;
import java.util.List;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
#RunWith(PowerMockRunner.class)
#PrepareForTest(SystemTray.class)
public class DisplayManagerTest {
#Mock
Log logMock;
#Mock
Runner runnerMock;
#Test
public void display_manager_does_nothing_if_system_tray_is_not_supported() throws IOException, AWTException {
mockStatic(SystemTray.class);
when(SystemTray.isSupported()).thenReturn(false);
new DisplayManager(runnerMock);
verifyZeroInteractions(runnerMock);
}
}
These are my maven dependencies
<powermock.version>1.5.2</powermock.version>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>

Just needed to change this line
#RunWith(PowerMockRunner.class)
to
#RunWith(DisplayManager.class)
According to this https://code.google.com/p/powermock/wiki/MockSystem

Here is a simple example using PowerMock:
package test;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.*;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.testng.IObjectFactory;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import demo.powermock.IdGenerator;
import demo.powermock.ServiceRegistartor;
//import org.easymock.classextension
#RunWith(PowerMockRunner.class)
#PrepareForTest(IdGenerator.class)
public class Test111 {
#ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
#Test
//#org.testng.annotations.Test
public void testRegisterService() throws Exception {
long expectedId = 42;
// We create a new instance of test class under test as usually.
ServiceRegistartor tested = new ServiceRegistartor();
// This is the way to tell PowerMock to mock all static methods of a
// given class
PowerMock.mockStatic(IdGenerator.class);
/*
* The static method call to IdGenerator.generateNewId() expectation.
* This is why we need PowerMock.
*/
expect(IdGenerator.generateNewId()).andReturn(expectedId);
// Note how we replay the class, not the instance!
PowerMock.replay(IdGenerator.class);
long actualId = new ServiceRegistartor().registerService();
// Note how we verify the class, not the instance!
PowerMock.verify(IdGenerator.class);
// Assert that the ID is correct
assertEquals(expectedId, actualId);
}
}

I had the same problem but I added the import manually the problem disappeared.
import org.powermock.modules.junit4.PowerMockRunner;

Related

Mock unit test a Service implementation that calls a Stored Procedure in Java

I’m trying to unit test a Service implementation that calls a Stored Procedure in Java.
My idea is to Mock or Stub the service just to see if all the calls are made correctly.
Not quite sure how to do this.
I’m using Springframework for the Service.
Any ideas on how to easily do this ? I'm getting null of course for the
#Autowired
private PerformanceService performanceService;
which doesn't initially happen, anyway I just want to Mock that and just make sure the calls are happening, thanks.
import com.integration.as400.entity.Performance;
import com.integration.as400.service.PerformanceService;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.BDDMockito.mock;
import static org.mockito.Mockito.when;
#Configuration
#RunWith(SpringRunner.class)
#SpringBootTest
#ContextConfiguration(classes={PerformanceService.class, TestConfiguration.class})
#ActiveProfiles("test")
public class PerformanceServiceImplMockTest {
private static final Logger logger = LoggerFactory.getLogger(PerformanceServiceImplMockTest.class);
#Autowired
private PerformanceService performanceService;
#Before
public void setupMock(){
MockitoAnnotations.initMocks(this);
performanceService = mock(PerformanceService.class);
}
#Test
public void shouldReturnListPerformance_whenGetListPerformanceIsCalled() throws Exception{
List<Performance> performances = new ArrayList<>();
performances.add(new Performance("0000184","00001","MWR","SI",LocalDate.parse("2016-01-01"),LocalDate.parse("2016-01-31"),"CAD",48585.63,34821.01,47501.47,-94372.00,11184.70,10.000322,"",33105.91));
performances.add(new Performance("0000184","00001","MWR","SI",LocalDate.parse("2016-01-01"),LocalDate.parse("2016-01-31"),"CAD",142743.11,260376.38,41688.49,-4886.00,11184.70,35937.14,"",7.475078));
logger.info("Stubbing getListPerformance(int pageNumber, String loadStartDate, String loadEndDate) to return " + performances);
// Arrange
when(performanceService.getListPerformance(2, "2021-08-01", "2021-08-31")).thenReturn(performances);
// Act
List<Performance> retrievedPerformances = performanceService.getListPerformance(2, "2021-08-01", "2021-08-31");
// Assert
assertThat(retrievedPerformances, is(equalTo(performances)));
}
}

#Before function is not fire in Junit test case

Here I have wrote a simple test case using Junit and Mockito.
import org.jbehave.core.annotations.Given;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import com.test.dao.login.LoginDao;
import com.test.mapping.user.User;
import com.test.service.login.LoginService;
import com.test.service.login.impl.LoginServiceImpl;
import com.test.util.common.Common;
public class UserLoginSteps {
#Mock
Common common;
#Mock
LoginDao loginDao;
#InjectMocks
LoginService loginService =new LoginServiceImpl();
#BeforeClass
public static void beforeClass() {
System.out.println("#BeforeClass");
}
#Before
public void before() {
System.out.println("#Before");
MockitoAnnotations.initMocks(this);
}
#After
public void after() {
System.out.println("#After");
}
#AfterClass
public static void afterClass() {
System.out.println("#AfterClass");
}
#Given("$username username and $password password")
#Test
public void checkUser(String username, String password) throws Exception{
when(common.checkNullAndEmpty("admin")).thenReturn(true);
when(common.checkNullAndEmpty("password")).thenReturn(true);
when(loginDao.getUser("admin","password")).thenReturn(new User());
assertEquals(true,loginService.checkValidUser(username, password));
}
}
I have initialize the Mock objects inside the before() function.
But that function is not triggered out in running the test case.
I am using following dependencies.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.8.9</version>
<scope>test</scope>
</dependency>
I have seen similar questions to this scenario.
But the following suggestions does not fix the issue.
Is any one can describe why it happen and how to fix this issue it will be great helpful.
Thanks in advance.
After-before-not-working-in-testcase
Simple-junit-class-is-not-calling-the-before-method
Why-isnt-my-beforeclass-method-running
You should annotate your class with #RunWith(MockitoJUnitRunner.class) So the MickitoJunitRunner will take care of your Mocks and tests. But it will not work like this together with JBehave. You have to decide if you want to use JBehave or MockitoJUnitRunner.
In JBehave the correct annotations to use are: #BeforeScenario #AfterScenario #BeforeStory #AfterStory Please take a look at jbehave doc: http://jbehave.org/reference/stable/annotations.html

JUnit Mock test returns null on using InjectMocks

I am trying to unit test my service class but the mock returns null
package com.tgt.store.pricetask.pricetask_service;
import com.tgt.store.pricetask.model.PriceTaskMaster;
import com.tgt.store.pricetask.model.TaskModel;
import com.tgt.store.pricetask.repository.PriceTaskMasterRepository;
import com.tgt.store.pricetask.service.DataMigrationService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.time.LocalDateTime;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
#RunWith(SpringJUnit4ClassRunner.class)
public class DataMigrationServiceTest {
#Mock
PriceTaskMasterRepository priceTaskMasterRepository;
#InjectMocks
DataMigrationService dataMigrationService;
#Test
public void
testPriceTaskMasterService_whenTaskModelPassed_thenSavePriceTaskMaster() {
TaskModel taskModel = new TaskModel.TaskModelBuilder().setTaskID(1)
.setDueDate("2017-11-01T11:41:00+0000").setIsAlertable("A").setIsPriority("P").setLocationid("1234")
.createTaskModel();
PriceTaskMaster priceTaskMaster = new PriceTaskMaster.PriceTaskMasterBuilder().setId(1L).setTaskStatus("A")
.setAlertable("A").setPriority("P").setLocationId(1234)
.setDueDate(LocalDateTime.now()).createPriceTaskMaster();
when(priceTaskMasterRepository.insertPriceTaskMaster(any(PriceTaskMaster.class))).thenReturn(priceTaskMaster);
PriceTaskMaster savedPriceTaskMaster = dataMigrationService.savePriceTaskMaster(taskModel);
assertNotNull(savedPriceTaskMaster);
assertEquals("A", savedPriceTaskMaster.getTaskStatus());
assertEquals("P", savedPriceTaskMaster.getPriority());
assertEquals(1234, savedPriceTaskMaster.getLocationId().intValue());
assertEquals(123456789, savedPriceTaskMaster.getTcin().longValue());
verify((priceTaskMasterRepository), times(1)).insertPriceTaskMaster(priceTaskMaster);
}
}
In the above code, when call reaches the service class priceTaskMasterRepository is null. I am unable to figure out if I am missing something. I have tried RunWith SpringRunner and MockitoJUnitRunner but same result. Any help is appreciated.
Thank you in advance.
You will need to initialize the DataMigrationService field when using the #InjectMocks annotation. That will create an instance of the class under test as well as inject the mock objects into it.
#InjectMocks
DataMigrationService dataMigrationService = new DataMigrationService();
http://www.baeldung.com/mockito-annotations
If you're using JUnit to run your tests, then you should have something like this:
#Before
public void setup()
{
MockitoAnnotations.initMocks(this);
}
This ensures all your mocks are initialised. This is supposed to be unnecessary when using MockitoJUnitRunner.

Powermock counts more than actually call when verify

Is it a bug of Powermock or I'm doing sth wrong?
The following test should pass, but failed with:
trackBugPartialMockCountMore(com.xiaomi.finddevice.test.testcase.PowerMockBug)
org.mockito.exceptions.verification.TooManyActualInvocations:
classToMock.foo();
Wanted 1 time:
-> at com.xiaomi.finddevice.test.testcase.PowerMockBug.trackBugPartialMockCountMore(PowerMockBug.java:24)
But was 3 times. Undesired invocation:
-> at com.xiaomi.finddevice.test.testcase.PowerMockBug.trackBugPartialMockCountMore(PowerMockBug.java:22)
When I remove #PrepareForTest(ClassToMock.class), every thing goes well and the test get passed.
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassToMock.class)
public class PowerMockBug {
#Test
public void trackBugPartialMockCountMore() {
ClassToMock mock = mock(ClassToMock.class);
when(mock.foo()).thenCallRealMethod();
mock.foo();
verify(mock).foo();
}
}
class ClassToMock {
public int foo() { return 0x10; }
}
VERSION: powermock-mockito-junit-1.6.3
In your example you don't need to use PowerMock because you are not mocking/spying a final or static method. You can safely remove both #RunWith and #PrepareForTest annotations. Only mockito is needed for your purposes

Can not convert from Class<PowerMockRunner> to Class<? extends Runner>

I am trying to write Unit test cases using power mockito.
When using annotations #RunWith(PowerMockRunner.class) I am getting the following compilation error:-
TypeMismatch: cannot convert from Class<PowerMockRunner> to Class<? extends Runner>
Here is the code snippet. Using junit 4.8.1 and power mock 1.6.2.
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
public class XXXTest {
#Test
public void testOne() {
if (true)
System.out.println("Success");
}
}
I downloaded and added Powermock-Module-Junit4 jar and did not add the dependent jar Powermock-Module-Junit4-Common.jar. When added common jar Powermock-Module-Junit4-Common resolved the error.
Thanks,
Vasu.

Categories

Resources