How to use PowerMock invoke private method and get return value? - mockito

I use PowerMockito mock a class instance that contains private method. And I want to verify private method return value is correct, So how to use PowerMock invoke private method and get return value?
This is demo:
class Demo {
public publicMethod1ReturnClass publicMethod1() {
// do something...
}
private privateMethod1ReturnClass privateMethod1() {
// do something
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(Demo.class)
class DemoTest {
#Test
public void test() throws Exception {
Demo demo = PowerMockito.spy(new Demo());
privateMethod1ReturnClass result = demo.privateMethod1();
}
}

You can do it using Whitebox like this,
privateMethod1ReturnClass s = Whitebox.invokeMethod(demo, "privateMethod1");
assertEquals(s, "yourExpectedResult");

Related

Unable to inject Captor with QuarkusTest

I am trying to write integration tests for Quarkus using Mockito, but I fail using Argument captor.
Here is a minimal (not) working example :
#QuarkusTest
#ExtendWith(MockitoExtension.class)
public class SimpleTest {
#Captor
private ArgumentCaptor<Context> contextArgumentCaptor;
#Test
public void testOne() {
System.out.println(contextArgumentCaptor);
}
}
contextArgumentCaptor is "null".
If I remove #QuarkusTest, contextArgumentCaptor is created.
It also works with #QuarkusTest and direct Argument creator :
#QuarkusTest
public class ConfigTest {
private ArgumentCaptor<Context> contextArgumentCaptor;
#BeforeEach
public void setup() {
contextArgumentCaptor = ArgumentCaptor.forClass(Context.class);
}
#Test
public void givenValidCloudEvent_whenHandleHandoverFunction_ThenHandoverStarted() {
System.out.println(contextArgumentCaptor);
}
}
So it is really the combinaison of #QuarkusTest with #Captor that doesn't work.
Any idea?
Yes, using #QuarkusTest along with the #Captor will not work correctly. You must create the captor yourself

how to convert return type of method within when().thenReturn method of Mockito

Below is my code snippet. This is giving me compilation error, as env.getProperty will return String. How do I get integer value. Interger.ParseInt is not working.
when(this.env.getProperty("NeededIntegerValue")).thenReturn(15);
Below is my test class
public class MyclassTest {
Myclass myObj=new Myclass();
#Mock Environment env=Mockito.mock(Environment.class);
#Before
public void init() {
when(this.env.getProperty("StringKey1")).thenReturn("Stringvalue");
when(this.env.getProperty("StringKey2")).thenReturn(intValue);
myObj.setEnvironment(this.env);
}
#Test
public void testTenantIdentifierCutomerTypeCUSTOMER_ACCOUNT() {
assertEquals("Expecteddata",myObj.testMethod(new StringBuilder(inputData),anotherData).toString);
}
}
Below is the Method needs to be tested
public StringBuilder testMethod(StringBuilder inputData, String anotherData)
{
if (anotherData.equals(env.getProperty("StringKey1"))) {
inputData=inputData.append(","+arrayOfInputData[Integer.parseInt(env.getProperty("intValue"))]);
}
}
First, you should mock your env, this way:
when(this.env.getProperty("StringKey1")).thenReturn("StringValue");
when(this.env.getProperty("StringKey2")).thenReturn("StringRepresentationOfYourInt");
Second, pay attention to the method itself, should be
arrayOfInputData[Integer.parseInt(env.getProperty("StringKey2"))
not
arrayOfInputData[Integer.parseInt(env.getProperty("intValue"))
Instead of
myObj.setEnvironment(this.env); in init() method try:
#InjectMocks
Myclass myObj = new Myclass();
Also remove assignment for
#Mock Environment env=Mockito.mock(Environment.class);
it should look
#Mock Environment env;

Creating anonymous object with inline function. Does it contain a leak of Enclosing Class?

As you know each anonymous object in java contains hidden reference to enclosing class.
But with kotling things get more complicated.
Lambda is another representation of anonymous class, but in kotlin it compiles not straightforward, because if lambda didn't capture a reference of enclosing class explicitely than it would be compiled like nested, not inner class (anonymous class) and is safe from the leak.
But what about inline functions. Consider the code below
class A {
fun test(){
val it = withReference {
//todo make sth
}
}
}
inline fun withReference(crossinline action: () -> Unit) = object: Reference {
override fun method1() {
action()
}
override fun method2() {
}
}
interface Reference {
fun method1()
fun method2()
}
As i know inline function would be compiled like non-wrapped code to the A class, so the question is open.
Does the anonymous object: Reference contain a link to enclosing class A, which could lead to a memory leak?
PS: i have read this article, but it doesn't contain an answer to my case
I used the decompiler of IntelliJ and there is no reference to the outer A
public final class A$test$$inlined$withReference$1 implements Reference {
public void method1() {
}
public void method2() {
}
}
If the lambda references a variable from the outer class A like this:
class A {
val valFromA = 10;
fun test(){
val it = withReference {
println("use $valFromA")
}
}
}
Then the decompiler shows the reference to the A object:
public final class A$test$$inlined$withReference$1 implements Reference {
// $FF: synthetic field
final A this$0;
public A$test$$inlined$withReference$1(A var1) {
this.this$0 = var1;
}
public void method1() {
String var1 = "use " + this.this$0.getValFromA();
System.out.println(var1);
}
public void method2() {
}
}
If you think about it, the withReference function has no way of referring to the outer scope that it gets inlined into, therefore it has no reason to contain a reference to the scope that it's called from. You don't even know what class it's being called in, or if it's even called inside a class, for that matter.
For this specific case, here's the decompiled and simplified bytecode of the withReference function:
public static Reference withReference(final Function0 action) {
return new Reference() {
public void method1() {
action.invoke();
}
public void method2() {
}
};
}
At the places where it gets inlined, there's of course no call to this function, this one is for Java interop only. Kotlin call sites all get their own class generated to represent this object depending on what code you pass into the action parameter. For your call of the test function, a class like is generated:
public final class A$test$$inlined$withReference$1 implements Reference {
public void method1() {
//todo make sth
}
public void method2() {
}
}
And this is what's instantiated in the test method:
public final class A {
public final void test() {
Reference it = new A$test$$inlined$withReference$1();
}
}

Mockito/PowerMockito: mock final static member cannot return different values in different methods

There is a final static member in class ToBeTestClass:
protected final static LMSServiceHelper externalService;
I mock it with
#Mock
protected LMSServiceHelper externalService;
Then I want to get different values in different test methods:
public void testMethod1() {
PowerMockito.when(externalService.getSomething).thenReturn("aaa");
}
public void testMethod2() {
PowerMockito.when(externalService.getSomething).thenReturn("bbb");
}
public void testMethod3() {
PowerMockito.when(externalService.getSomething).thenReturn("ccc");
}
However, I can't get "bbb" or "ccc" whereas always get "aaa". It seems when I set the return value first time, and it will never changes.
Anyone has met this?
#Before
public void setUp() {
Mockito.when(externalService.getSomething)
.thenReturn("aaa")
.thenReturn("ccc")
.thenReturn("ccc"); //any subsequent call will return "ccc"
}
How to tell a Mockito mock object to return something different the next time it is called?
Reset your mocked object as shown below then you will see different values
public void testMethod1() {
PowerMockito.when(externalService.getSomething).thenReturn("aaa");
Mockito.reset(externalService);
}
public void testMethod2() {
PowerMockito.when(externalService.getSomething).thenReturn("bbb");
Mockito.reset(externalService);
}
public void testMethod3() {
PowerMockito.when(externalService.getSomething).thenReturn("ccc");
Mockito.reset(externalService);
}

Mockito - Testing method that calls private methods

I was trying to find solution but haven't found yet. I tried to test public method which has calls of the couple of private ones inside. One of the problem that private method retrieves Hibernate's Criteria by generic method that in its turn retrieves it through chain of another generic methods. Please take a look at the code below. Frankly I'm not sure that it is possible to test that case but if anyone has ideas please suggest them:
ConcreteDao
public class ConcreteDao extends EntityDao<ConcreteEntity> {
public Class<ConcreteEntity> getClassType() {
return ConcreteEntity.class;
}
}
EntityDao
public abstract class EntityDao<T> extends AbstractDao<T>{
public List<T> getEntityByFilter(EntityFilter filter) {
Criteria criteria = getCriteriaByFilter(filter.getFilters());
criteria.setMaxResult(filter.getMaxResult());
criteria.setFirstResult(filter.getFirstResult());
criteria.addOrder(Order.asc(filter.getSortedField()));
criteria.list();
}
private Criteria getCriteriaByFilter(List<CustFilter> filters) {
Criteria criteria = getCriteria();
for (CustFilter filter : filters) {
filter.addrestrictionToCriteria(criteria, filter.getProperty(), filter.getValue());
}
return criteria;
}
}
AbstractDao
public abstract class AbstractDao<T> {
private EntityManagerFactory entityManagerFactory;
public abstract getClassType();
public Criteria getCriteria() {
return getSession().createCriteria(getClassType());
}
public Session getSession() {
Session session = (Session) getEntityManager().getDelegate();
return session;
}
public EntityManager getEntityManager() {
entityManagerFactory.getEntityManager();
}
}
Test class
#RunWith(MockitoJUnitRunner.class)
public class ConcreteDaoTest {
#Mock
private EntityManager entityManager;
#Mock
private Session session;
#Mock
private Criteria criteria;
private List<CustFilter> filters;
private EntityFilter entityFilter;
private List<ConcreteEntity> resultList;
#InjectMocks
private ConcreteDao concreteDao = new ConcreteDao;
public void init() {
filters = new ArrayLis<CustFilter>();
CustFilter custFilter = new CustFilter();
//fill filter;
filters.add(custFilter);
entityFilter = new EntityFilter();
//fill entityFilter
entityFilter.setFilters(filters);
ConcreteEntity concreteEntity = new ConcreteEntity();
resultList = new ArrayList<ConcreteEntity>();
resultList.add(concreteEntity);
}
#Test
public void getEntityByFilterTest() {
when(concreteDao.getEntityManager).thenReturn(entityManager);
when(concreteDao.getSession()).thenReturn(session);
when(concretedao.getCriteria()).thenReturn(criteria);
when(filter.getFilters()).thenReturn(filters);
when(filter.getMaxResult()).thenReturn(10);
when(filter.getFirstResult()).thenReturn(0);
when(filter.getSortedField()).thenReturn("firstName");
when(criteria.list()).thenReturn(resultList);
List<ConcreteEntity> result = concreteDao.getEntityByFilter(entityFilter);
Assert.assertThen(result. is(notNullValue()));
}
}
With Mockito, you cannot mock private method calls.
Try PowerMockito with which you can mock any kinds of methods like static methods, private methods, local method instantiations and so on.

Resources