PowerMockito.whenNew is not working - java

Hi folks i am new to PowerMockito and i am trying to use whenNew in PoweMockito and its not working for me, can anyone please help me out with this??
Below is my Test method which is used to test Class2, and i have Used PowerMockito.whenNew for mocking mockTestMethod inside Class2 and return String Value as "MOCKED VALUE" but that is not happening and actually the method is being executed and output is "PassedString".
If i am not wrong the Output should have string as "Inside Class2 method MOCKED VALUE" but i am getting output as "Inside Class2 method PassedString."
Please help me with the issue,
Thanks In Advance.
Below is the complete program which i am working on
package com.hpe.testing2;
public class Class2 {
public void testingMethod(){
Class1 class1 = new Class1();
String result = class1.mockTestMethod("PassedString");
System.out.println("Inside Class2 method " + result);
}
}
package com.hpe.testing2;
public class Class1 {
public String mockTestMethod(String str2){
String str1="SomeString";
str1 = str2;
System.out.println("Inside MockTest Method " + str1);
return str1;
}
}
class2 is invoking Class1 mockTestMethod internally as shown above.
package com.hpe.testing2;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest({Class2.class,Class1.class})
public class ClassTest {
public static void main(String[] args) throws Exception {
ClassTest testing = new ClassTest();
testing.runMethod();
}
public void runMethod() throws Exception{
Class2 class2 = new Class2();
Class1 class1 = PowerMockito.mock(Class1.class);
PowerMockito.whenNew(Class1.class).withAnyArguments().thenReturn(class1);
PowerMockito.when(class1.mockTestMethod(Mockito.anyString())).thenReturn("MOCKED
VALUE");
class2.testingMethod();
}
}

You cannot start a test class via main method. Instead it should be run with JUnit. Therefore a #Test annotation has to be present at the test method. Look here for getting started with JUnit.
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Class2.class, Class1.class })
public class ClassTest {
#Test
public void runMethod() throws Exception {
Class2 class2 = new Class2();
Class1 class1 = PowerMockito.mock(Class1.class);
PowerMockito.whenNew(Class1.class).withAnyArguments().thenReturn(class1);
PowerMockito.when(class1.mockTestMethod(Mockito.anyString())).thenReturn("MOCKED VALUE");
class2.testingMethod();
}
}
(I left out imports in your testclass)

Related

How to mock a nested function?

I have this following class A. It has two functions Barney and Ted. Barney calls Ted from inside. How to mock Ted's behavior in my test class?
package MockingNestedFunction;
import java.util.ArrayList;
import java.util.List;
public class A
{
public String Barney()
{
List<String> x =Ted();
String a="";
for(int i=0;i<x.size();i++)
{
a=a.concat(x.get(i));
}
return a;
}
public List<String> Ted()
{
List<String> x=new ArrayList<>();
x.add("A");
x.add("B");
x.add("C");
return x;
}
}
package MockingNestedFunction;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.when;
import static org.testng.Assert.*;
public class ATest
{
private A a;
#BeforeMethod
public void setup()
{
MockitoAnnotations.openMocks(this);
a=new A();
}
#Test
public void testA() throws Exception
{
List<String> x=new ArrayList<>();
x.add("D");
x.add("E");
x.add("F");
when(a.Ted()).thenReturn(x);
}
}
when(a.Ted()).thenReturn(x) returns the error,when() requires an argument which has to be 'a method call on a mock'.
How to effectively mock this?
You dont pass a method call on a mock to Mockito.when, as error message helpfully says. You are passing a method call on a object you created yourself.
If you need to stub some methods of the object under test, you are looking for a spy.
#Spy
private A a;
#BeforeMethod
public void setup() {
MockitoAnnotations.openMocks(this);
}
As others noted in comments, stubbing some methods on object under test is a questionable practice, if you can think about restructuring the code.
On top of that: Let's keep the terminology precise. There are no nested functions in your code.

Mockito - Verifying if a method calls another method within the same class

I am trying to test whether a method calls another method within the same class. Example:
public class Foo {
public void bar(String a){
switch(a) {
case "callBaz":
baz(a);
break;
case "callBat":
bat(a);
break;
default:
System.out.println("Input was " + a);
}
}
public void baz(String b){
System.out.println(b);
}
public void bat(String c){
System.out.println(c);
}
}
However if I try mockito verify on the class itself:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
#Test
public void testBazCalledFromBar(){
Foo foo = new Foo();
foo.bar("callBaz");
Mockito.verify(foo).baz("callBaz");
}
}
I get the exception:
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to verify() is of type Foo and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
verify(mock).someMethod();
verify(mock, times(10)).someMethod();
verify(mock, atLeastOnce()).someMethod();
When using the mock:
...
#RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
#Test
public void testBazCalledFromBar(){
Foo fooMock = Mockito.mock(Foo.class);
fooMock.bar("callBaz");
Mockito.verify(fooMock).baz("callBaz");
}
}
I get the exception:
Wanted but not invoked:
foo.baz("callBaz");
-> at com.mn.stagportal.view.employee.FooTest.testBazCalledFromBar(FooTest.java:15)
However, there were other interactions with this mock:
foo.bar("callBaz");
-> at com.mn.stagportal.view.employee.FooTest.testBazCalledFromBar(FooTest.java:13)
Does anyone know how to test if baz("callBaz") is called?
This should work.
#RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
#Test
public void testBazCalledFromBar(){
Foo fooMock = Mockito.mock(Foo.class);
doCallRealMethod().when(fooMock).bar(anyString());
fooMock.bar("callBaz");
Mockito.verify(fooMock).baz("callBaz");
}
}
The issue is, since fooMock is a mock, when it encounters this line
fooMock.bar("callBaz");
It doesn't know what to do. You need to tell Mockito, whether you want to mock the method call or you want to call the real method.
Verify can only work if the code flow goes to this real method and called the baz method.
You shouldn't mock the tested object, you can spy instead:
#RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
#Test
public void testBazCalledFromBar(){
Foo foo = Mockito.spy(Foo.class);
foo.bar("callBaz");
Mockito.verify(foo).baz("callBaz");
}
}
or
#RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
#Test
public void testBazCalledFromBar(){
Foo foo = Mockito.spy(new Foo(/* params */));
foo.bar("callBaz");
Mockito.verify(foo).baz("callBaz");
}
}

How To Set Up PowerMockito To Verify Different Types of Methods Are Called?

Please provide minimal examples of using PowerMockito to test public, public static, private, and private static methods.
Here's an extremely stripped down example ("SSCCE") of using PowerMockito to verify four types of methods have been called from another method: public, public static, private, and private static.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(com.dnb.cirrus.core.authentication.TestableTest.Testable.class)
public class TestableTest {
public static class Testable {
public void a() {
b();
c();
d();
e();
}
public void b() {
}
public static void c() {
}
private void d() {
}
private static void e() {
}
}
Testable testable;
// Verify that public b() is called from a()
#Test
public void testB() {
testable = Mockito.spy(new Testable());
testable.a();
Mockito.verify(testable).b();
}
// Verify that public static c() is called from a()
#Test
public void testC() throws Exception {
PowerMockito.mockStatic(Testable.class);
testable = new Testable();
testable.a();
PowerMockito.verifyStatic();
Testable.c();
}
// Verify that private d() is called from a()
#Test
public void testD() throws Exception {
testable = PowerMockito.spy(new Testable());
testable.a();
PowerMockito.verifyPrivate(testable).invoke("d");
}
// Verify that private static e() is called from a()
#Test
public void testE() throws Exception {
PowerMockito.mockStatic(Testable.class);
testable = new Testable();
testable.a();
PowerMockito.verifyPrivate(Testable.class).invoke("e");
}
}
Some pitfalls to be aware of:
PowerMockito and Mockito both implement spy() as well as other methods. Make sure to use the correct class for the situation.
Incorrectly set up PowerMockito tests often pass. Be sure the test can fail when it should (checked for in the above code by commenting out "testable.a()").
Overridden PowerMockito methods take either Class or Object as parameters which are used in static and non-static contexts respectively. Make sure to use the correct type for the context.

calling methods from different package JAVA

I have two packages; pack1 and pack2.
in pack1 I have two classes the main called Prog and another one called ClassA.
In pack2 I have one class called ClassB.
I am trying to understand why I can't call a method from ClassB using the object.
I can do that using the main class but not with another class.
Here's the code:
package pack1;
import pack2.ClassB;
public class Prog {
public static void main(String[] args){
}
}
Code for ClassA
package pack1;
import pack2.ClassB;
public class ClassA {
ClassB o3 = new ClassB();
// Error won't compile
System.out.println(o3.getText());
}
Code for ClassB:
package pack2;
public class ClassB {
final String TEXT = "This is a text";
public String getText(){
return TEXT;
}
}
The problem here isn't that you can't access the method. The problem is that statements must be enclosed either in a constructor, amethod-declaration or an initializer-block. So this would be valid code for example:
enter codepackage pack1;
import pack2.ClassB;
public class ClassA {
ClassB o3 = new ClassB();
public void someMethod(){
System.out.println(o3.getText());
}
}
//pack1 code here
package pack1;
import pack2.ClassB;
class ClassA {
}
public class Prog {
public static void main(String[] args) {
// write your code here
ClassB o3 = new ClassB();
// Error won't compile
System.out.println(o3.getText());
}
}
//pack2 code here
package pack2;
public class ClassB {
final String TEXT = "This is a text";
public String getText() {
return TEXT;
}
}
You don't need to create class A you can directly import pack2 and its class, method

Using Mockito to mock a class method inside another class

I'm trying to write unit tests with Mockito / JUnit for a function like this:
class1 {
method {
object1 = class2.method // method that I want to fake the return value
// some code that I still want to run
}
}
Is there any way in Mockito to stub the result of class2.method? I'm trying to improve code coverage for class1 so I need to call its real production methods.
I looked into the Mockito API at its spy method but that would overwrite the whole method and not the part that I want.
I think I am understanding your question. Let me re-phrase, you have a function that you are trying to test and want to mock the results of a function called within that function, but in a different class. I have handled that in the following way.
public MyUnitTest {
private static final MyClass2 class2 = mock(MyClass2.class);
#Begin
public void setupTests() {
when(class2.get(1000)).thenReturn(new User(1000, "John"));
when(class2.validateObject(anyObj()).thenReturn(true);
}
#Test
public void testFunctionCall() {
String out = myClass.functionCall();
assertThat(out).isEqualTo("Output");
}
}
What this is doing is that within the function wrapped with the #Before annotation, I am setting up how I want the functions in class2 to respond given specific inputs. Then, from within the actual test, I am just calling the function that I am trying to test in the class I want to test. In this case, the myClass.functionCall() is running through as normal and you are not overwriting any of its methods, but you are just mocking the outputs that it gets from the methods (or method) within MyClass2.
This Worked for Me:
public class Class1Test {
Class1 class1;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
class1 = new Class1();
}
#Test
public void testClass1Method() {
Class2 class2 = Mockito.mock(Class2.class);
class1.setClass2(class2);
Mockito.when(
class2.class2Method(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("some response");
String actualResponse = class1
.class1Method("12345", "3333", "4444");
assertEquals("some response", actualResponse);
}
}
I wrote a simple example which worked fine, hope it helps:
method1() from Class1 calls method2() from Class2:
public class Class1 {
private Class2 class2 = new Class2();
public int method1() {
return class2.method2();
}
}
Class2 and method2() :
public class Class2 {
public int method2() {
return 5;
}
}
And the Test:
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
public class TestClass1 {
#Mock
Class2 class2;
#InjectMocks
Class1 class1;
#Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
#Test
public void testMethod1(){
when(class2.method2()).thenReturn(29);
assertEquals(29,class1.method1());
}
}

Categories

Resources