How to mock static with PowerMock without using PowerMockRunner? - powermock

#Runner doesn't play well with #ClassRule so I'm trying to use:
#ClassRule
public static PowerMockRule rule = new PowerMockRule();
But then #PrepareForTest does nothing.
My code looks something like:
#PrepareForTest({SomeClass.class})
public class DynamicVipTest {
#ClassRule
public static SomeClassRule someClassRule = new SomeClassRule();
#ClassRule
public static PowerMockRule rule = new PowerMockRule();
#BeforeClass
public static void setupClass() {
PowerMock.mockStatic(SomeClass.class);
expect(SomeClass.someMethod().andReturn("someValue").anyTimes();
}
}
The expect winds up calling SomeClass.someMethod rather than creating an expectation.
What's the latest and greatest way to mock statics?

Hopefully, there's a better 'solution' than the following:
#RunWith(PowerMockRunner.class)
#PrepareForTest({SomeClass.class})
public class DynamicVipTest {
public static SomeClassRule someClassRule = new SomeClassRule();
#ClassRule
public static PowerMockRule rule = new PowerMockRule();
#BeforeClass
public static void setUpClass() {
someClassRule.before();
PowerMock.mockStatic(SomeClass.class);
expect(SomeClass.someMethod().andReturn("someValue").anyTimes();
}
#AfterClass
public static void tearDownClass() {
someClassRule.after();
}
}

Related

Mocking object from another class

I have a service class that starts a service.
This service should only start between a certain time.
So i need to mock this , but it does not work.
My Time class:
public boolean isTimeBetween_00_06(){
return Instant.now().isBefore(Instant.now()
.truncatedTo(ChronoUnit.DAYS)
.plus(6,ChronoUnit.HOURS));
}
My Service class:
start(){
if(! new MyTimeUtils().isTimeBetween_00_06){
throw new Exception;
}
}
My test class:
#InjectMocks
private MyServiceClass service;
#Mock
private MyTimeUtils myTimeUtils;
#Test
myTest(){
Mockito.when(myTimeUtils.isCurrentTimeBetween_00_06()).thenReturn(true);
service.start();
}
I expect that I get the right assert, but it stops with Exption.
I also tryed PowerMockito but still it did not work.
Someone have an idea?
Best Regards.
You should inject MyTimeUtils instead of instance creation in the method.
And don't forget #RunWith(MockitoJUnitRunner.class);
Have a look at the code, please:
public class MyServiceClass {
private final MyTimeUtils myTimeUtils;
public MyServiceClass(MyTimeUtils myTimeUtils) {
this.myTimeUtils = myTimeUtils;
}
public void start() {
if (!myTimeUtils.isTimeBetween_00_06()) {
throw new IllegalStateException("ERROR");
}
}
}
#RunWith(MockitoJUnitRunner.class)
public class MyServiceClassTest {
#InjectMocks
private MyServiceClass service;
#Mock
private MyTimeUtils myTimeUtils;
#Test
public void myTest(){
Mockito.when(myTimeUtils.isTimeBetween_00_06()).thenReturn(true);
service.start();
}
}

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();
}
}

I need to write JUNIT for Apache camel route

I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this
You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}

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();