How to mock a call of an inner method from a Junit - java

I have MyClass and I am doing a test-class for every method (Method1Test)
public class MyClass {
public int method1(){
int a = method2();
return a;
}
public int method2(){
return 0;
}
}
#RunWith(MockitoJUnitRunner.class)
public class Method1Test {
#InjectMocks
private MyClass myClass = new MyClass();
#Before
public void setup(){}
#Test
public void test01(){
Mockito.when(myClass.method2()).thenReturn(25);
int a = myClass.method1();
assertTrue("We did it!!!",a==25);
}
}
The problem is that I am not able to mock the call to method2 to make it return a diferent value. The Mockito sentence don't do the work.
Very thanks ^_^

You have to create a spy on the class-under-test and partially mock it by redefining the behavior for the method2() of the spy
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
public class Method1Test {
private MyClass myClass = new MyClass();
#Test
public void test01(){
//given
MyClass spy = spy(myClass); //create a spy for class-under-test
when(spy.method2()).thenReturn(25); //partially override behavior of the spy
//when
int a = spy.method1(); //make the call to method1 of the _spy_!
//then
assertEquals(25, a);
}
}
Apart from this, you don't require neither the Mockito Runner nor the #InjectMocks for your test as you're doing no injection of #Mock annotated mocks into the class-under-test.
Further, the message in the assertTrue statement is only displayed, when the condition of the assertion is NOT fulfilled. So it should be at least "We failed!!!" ;)

In the end I find a transversal solution without create a new class (I haven't been able to do it because it is forbbiden in the actual project). I have overwrited the method in the test.
The solution is
public class MyClass {
public int method1(){
int a=0;
a=method2();
return a;
}
public int method2(){
return 1;
}
}
#RunWith(MockitoJUnitRunner.class)
public class Method1Test {
#InjectMocks
private MyClass myClass = new MyClass(){
public int method2(){
return 25;
}
};
#Before
public void setup(){}
#Test
public void test001(){
Mockito.when(myClass.method2()).thenReturn(25);
int a = myClass.method1();
assertTrue("We did it!!!",a==25);
}
}

I tried the solution using the code below, but It didn't pass.
Mockito.when(myClass.method2()).thenReturn(25);
Afterwards, Instead of the code snippet above, I tried something different and the test passed successfully. Take a look:
Mockito.doReturn(25).when(myClass).method2();
In order to mock a test (It might be a inner method), you have to use doReturn() method.
You can use doThrow(), doAnswer(), doNothing(), doReturn() and doCallRealMethod() in place of the corresponding call with when(), for any method. It is necessary when you
stub void methods
stub methods on spy objects (see below)
stub the same method more than once, to change the behaviour of a mock in the middle of a test.
but you may prefer to use these methods in place of the alternative
with when(), for all of your stubbing calls.
Furthermore information can be read here https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#12

Instead of using mock(class) here we need to use Mockito.spy() to mock the same class we are testing. Then we can mock the method we want as follows.
#Test
public void method1Test() {
MyClass myClass = new MyClass();
MyClass myClass1 = Mockito.spy(myClass);
Mockito.doReturn(1).when(myClass1).method2();
Assert.assertEquals(1, myClass1.method1());
}
}

Related

How to mock enum singleton with jmockit?

I have a dependency on an enum singleton class like
public enum SingletonObject {
INSTANCE;
SingletonObject() {
// some annoying initialization
}
public callDB() {
this.num = num;
}
}
I am trying to test a class like
public class MyClass {
public void doSomething() {
// some code
SingletonObject.INSTANCE.callDB();
}
}
Following this answer, I've tried simply testing the mock with the following code, but I seem to be running into problems with the enum calling its constructor
public class MyClassTest {
#Mocked
private SingletonObject singleton;
#Before
public void setup() {
Deencapsulation.setField(SingletonObject.class, "INSTANCE", singleton);
}
#Test
public void test() {
assertSame(singleton, SingletonObject.INSTANCE);
}
}
Using an interface seems somewhat promising, but I question whether that is the best way of going about this problem.
It looks like PowerMockito is promising as well, but I would like to save that as a last resort for various reasons.
So how can I mock this enum singleton without invoking its constructor?
Try something like this. This creates a partial-mock of 'MyClass' and a Mock SingletonObject, calls the (real) doSomething method of MyClass, and confirms that the (mock) callDB() method of SingletonObject is invoked by it precisely once.
#Test
public void testdoSomething(
#Mocked final SingletonObject singleton)
{
final MyClass clz = new MyClass();
new Expectations(clz)
{
{
SingletonObject.INSTANCE.callDB();
times = 1;
}
};
clz.doSomething();
}

How to implement doNothing() for static void method?

Am trying to mock one static void method, I tried PowerMock but always getting NullPointer exception.
We are trying to mock the below call -
public Class XYZ{
public void method1(){
....
SampleClass.methodTypeStatic1().methodTypeStatic2("xyz", "mno", classVeriable);
}
And the main class is -
public class SampleClass implements SampleClassParent{
private static SampleClass var1;
public static SampleClass methodTypeStatic1(){
if (var1 == null) {
//Do something on var1
}
return var1;
}
public void methodTypeStatic2(String localVar1, String localVar2, DifferentStaticClass localVar3) {
//Do something
}}
Am trying to mock the call like this way in my test class -
#RunWith(PowerMockRunner.class)
#PrepareForTest({SampleClass.class})
public class XYZTest{
#InjectMocks
XYZ xyzTestService;
#Test
public void testMethod1(){
...
PowerMockito.mockStatic(SampleClass.class);
PowerMockito.doNothing().when(SampleClass.methodTypeStatic1());
xyzTestService.method1();
}
Also to be mentioned SampleClass.class is not a part of our code, we have imported this external class into our code base to perform some task.
If you want to mock a non-void method, you need to define the behaviour for this method on the mock. You get the doNothing for free (as this is what mocking does),
however you need to define what the method is supposed to return.
Your test could look like this:
#Test
public void testMethod1() {
SampleClass sample = new SampleClass();
PowerMockito.mockStatic(SampleClass.class);
PowerMockito.when(SampleClass.methodTypeStatic1()).thenReturn(sample);
XYZ xyzTestService = new XYZ();
xyzTestService.method1();
}
You didn't not mention any #Mock annotations, so using #InjectMocks does nothing for you besides creating the XYZ object.

Mock inherited protected method

I here have a simplified version of my problem. Class A has a protected method. Class B inherits this method.
public class A{
protected String getString(){
//some Code
}
}
public class B extends A{
public void doSomething(){
//someCode
String result = getString();
}
}
I now write a Unit-Test with Mockito, which is in another package-test and I want to test the doSomething() method. To do that, I need to mock the getString()-call. Since the method is protected and my test-class is in a differnet package, I can't use doReturn(...).when(classUnderTest).getString(). The thing is, that I spy on class B. So I can't use mock(new B(), Mockito.CALLS_REAL_METHODS).
I tried getting the protected method via Reflection:
Method getString = classUnderTest.getClass().getDeclaredMethod("getString");
getString.setAccessible(true);
But I then don't know how to use this inside doReturn().
You can use 'override and subclass'
B b = new B() {
#Override
protected String getString() {
return "FAKE VALUE FOR TESTING PURPOSES";
};
};
There might be a cleaner way of doing this, but here goes...
Create a mock for "A"
Create another class that extends B and overrides the method
Make the overridden method call the mock
For example...
private A partialMock;
private B classUnderTest;
#Before
public void setup() {
partialMock = mock(A.class);
classUnderTest = new B() {
#Override
protected String getString() {
return partialMock.getString();
}
};
}
#Test
public void shouldDoSomething() {
when(partialMock.toString()).thenReturn("[THE MOCKED RESPONSE]");
classUnderTest.doSomething();
// ...verify stuff...
}
Obviously you don't even need to use mocking, you can just return something directly from the overridden method.
Something like following worked for me, using doReturn() and Junit5's ReflectionSupport.
[Note: I tested on Mockito 3.12.4]
var a = spy(new A);
ReflectionSupport.invokeMethod(
a.getClass().getSuperclass().getDeclaredMethod("getString"),
doReturn("FAKE VALUE FOR TESTING PURPOSES").when(a));

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

how to mock a void method in powermock

How to mock a void method which is non-static, non-finalThe signature of method is as below. I'm using Powermockito.
public class Name{
public void methodName{
...
...
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest({Name.class})
public class TestClass{
#Test
public void testMethodName(){
PowerMockito.doNothing().when(Name.class, methodName);
//some when calls after this and assert later on
}
I want to DO Nothing when methodName is called. the above code is not working. it says methodName cannot be resolved.
if you want to mock a non-static method you need to specify the mock object:
public class Name{
public void methodName{
...
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest({Name.class})
public class TestClass{
#Test
public void testMethodName(){
Name myName = PowerMockito.mock(Name.class);
PowerMockito.doNothing().when(myName).methodName();
//some when calls after this and assert later on
}
}
You can Use PowerMock.createmock() for Mocking your Class Where method is There.
For e.g you have ClassA and methodA which is a Void Method.
Then You can Mock it in a below way:
A a = PowerMock.CreateMock(A.class);
a.methodA();
PowerMock.replay(a);
Note : in above case method a is void That's the reason EasyMock.expect is not return;
I'm not at an IDE at the moment, but I think you can do this:
final Name name = mock(Name.class);
doNothing().when(name).methodName();

Categories

Resources