I have a function like this:
@Override
public ClassA createViewModel(ClassB product, ClassC classCVar)
throws ModuleException
{
ClassA classAVar = ClassA.builder().build();
try {
if (product != null && product.getProductData() != null) {
String gl_name = product.getProductData().offers().get(0).productCategory().asProductCategory()
.inlined().map(ProductCategory::glProductGroup).map(ProductCategory.GLProductGroup::symbol)
.orElse("");
classAVar.setName = gl_name;
}
return classAVar;
} catch (Exception e) {
// some lines of code.
}
I have a line here like String gl_name = ............ which contains a chain of method calls. Now I want to mock this function using Mockito and want a final result out of all these function calls simply like gl_name = "abc";
How can I do this?
I have created a new function and had put the chain of method calls inside it like this:
public String fetchGLNameFunction(ClassB product)
{
String gl_name_result = product.getProductData().offers().get(0).productCategory().asProductCategory()
.inlined().map(ProductCategory::glProductGroup).map(ProductCategory.GLProductGroup::symbol)
.orElse("");
return gl_name_result;
}
And now I have tried to create a mock like this:
@Mock
private ClassA classAVar;
..........
............
@Test
public void testfunction1() throws Exception
{
when(classAVar.fetchGLNameFromAmazonAPI(classBVar)).thenReturn("abc");
It is still giving me NullPointerException because it is executing my newly created function.
In Mockito
you need to define the behavior of your mock objects.
// create mock
ClassB product = mock(ClassB.class);
// Define the other mocks from your chain:
// X, Y, Z, ...
// define return value for method getProductData()
when(product.getProductData()).thenReturn(X);
when(X.offers()).thenReturn(Y);
when(Y.get(0)()).thenReturn(Z); // And so on.... until the last mock object will return "abc"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With