how to convert return type of method within when().thenReturn method of Mockito - 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;

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

Springboot mockito mock a field

I want to mock the TreeMap in Service class, I tried to mock using TreeMap<String, String> requestsMap = Mockito.mock(TreeMap.class); But the map is getting null at runtime.
#RunWith(SpringRunner.class)
#SpringBootTest
#WebAppConfiguration
public class ServiceTest {
#InjectMocks
private Service service;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
}
#Test
public void test() {
TreeMap<String, String> requestsMap = Mockito.mock(TreeMap.class);
}
}
#Service
public class Service {
private TreeMap<String, String> requestsMap = null;
}
Your Service class doesn't actually do anything but declare and initialize the requestMap to null. Also, your test method doesn't do anything other than declare a mock requestMap.
In addition to the code you have, write a method in the Service that uses the request map and just declare/autowire the requestMap. In your test, use the #Mock annotation on a declaration of your mock requestMap. Finally, use the mocked requestMap in your test.
For example:
#RunWith(SpringRunner.class)
#SpringBootTest
#WebAppConfiguration
public class ServiceTest {
#Mock
TreeMap<String, String> requestsMap;
#InjectMocks
private Service service;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
}
#Test
public void test() {
when(requestMap.get("foo")).thenReturn("bar");
String result = service.doSomething();
assertEquals(result, "bar");
}
}
#Service
public class Service {
#Autowired
private TreeMap<String, String> requestsMap;
public String doSomething() {
return requestMap.get("foo");
}
}

When clause in Mockito JUnit is not working while calling method of testing class

I am trying to stub method of testing class. And it is not working.
Like am testing below class
enter code here
Class to test:
public Class A{
public String method1(){
C c=new C();
int num=c.methodC();
B b=new B();
String str=method2(b);
return str;
}
public String method2(B b){
String str=method2(b);
return str;
}
}
JUnit class:
#RunWith(JUnitPlatform.class)
Class ATest {
#InjectMocks
A a;
#Mock
C c;
#Mock
A a1;
#BeforeEach
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testMethod1(){
Mockito.doReturn(34).when(c).methodC(anyString());
a1=Mockito.mock(A.class);
Mockito.doReturn("Added successfully").when(a1).method2(any(B.class));
assertEquals("Added successfully", a.method1());
}
}
When am stubbing methodC(...) from Class C it is working. But method2(...) from Class A is not stubbing.
Please let me know what is the issue, and solution.
You have 2 options to mocka parts of the object.
Option 1: use a #Spy instead of a #Mock
#ExtendWith(MockitoExtension.class)
class ATest {
#Spy
A a;
#Test
public void testMethod1() {
Mockito.doReturn("Added successfully").when(a).method2(any(B.class));
assertEquals("Added successfully", a.method1());
}
}
Option 2: Use a mock and mark real implementations
#ExtendWith(MockitoExtension.class)
class ATest {
#Mock
A a;
#Test
public void testMethod1() {
Mockito.doReturn("Added successfully").when(a).method2(any(B.class));
Mockito.doCallRealMethod().when(a).method1();
assertEquals("Added successfully", a.method1());
}
}
I found via trial and error method that, methods in testing class cannot be mocked. In case we have to mock a method, either we have to move such methods to different class, or do not mock it. That is the only solution.

Method inside "When" actually being called

When I am testing a class A (TestNG) which uses some methods from some other class Helper Class
I am mocking the helper class(Mockito) for testing class A.
but when(helper.methodUsedByClassA(value)).thenReturn(new HashMap>())
this line of code is actually calling helper.methodUsedByClassA and a null pointer exception is thrown (because of data I am using for testing is not valid)
why is this happening? Why would the method name inside mockito "when" actually be called ?
class ATest{
#Mock
private Helper helper;
private A target;
#BeforeTest
public void setUp() {
MockitoAnnotations.initMocks(this);
this.target = new UpdateDigicatKdpAsinUtil(helper);
}
#Test(dataProvider = "data")
public void testMethod(List<String> value) {
when(helper.methodUsedByClassA(value)).thenReturn(new HashMap<String, List<String>>({{put("test", new ArrayList<>())}}));
}
#DataProvider
public Object[][] data(){
List<String> list = new ArrayList<>();
return new Object[][]
{
{list}
}
}
class Helper{
public Map<String, List<String>> methoUsedByClassA(int value) {
//This method is being executed because it is mentioned inside "when"
}
}
I guess you get an NPE because helper is NULL.
The problem is that the #Mock annotation isn't processed and because of that, the variable helper isn't initialized.
You have to annotate the test class with #RunWith(MockitoJUnitRunner.class). MockitoJUnitRunner will process the #Mock annotation and create the mock.

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

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

Resources