Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock chain of method calls using Mockito

Tags:

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.

like image 447
user3608245 Avatar asked Apr 15 '18 08:04

user3608245


1 Answers

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"
like image 175
Roni Koren Kurtberg Avatar answered Sep 28 '22 17:09

Roni Koren Kurtberg