How to unit test code blocks in spring boot

288 views Asked by At

I have unit test in spring boot written using junit and mockito . I have method that has uses method which take code block as input and perform required function . Below is sample example of code.

class A{
    execute(Codeblock codeblock){
      
    }

   }
 


Class B {
    
   
  C testFunction(){
     return A.execute(()->{
               code to execult ...;
              });
    }
  
  }

class TestB{
    @InjectMock
   B b;
    @Mock
   A a;
 void testFunction(){
    when(A.execult(any())).return(C);
    AssertNotNull(b.testFunction());
    }
}

This code is running fine but code coverage is very low because code block is not execute. Is there any way to execute code block and increase coverage.

1

There are 1 answers

0
Beppe C On

Testing your class (B) using mocks (A) is correct, the goal is to test any logic in B and verify the interactions with the collaborators (in this case A).

I would then create test for A (mocking Codeblock class), applying the same principle as above.

Finally I would test Codeblock logic independently.