junit nested mock injections for characterization tests

I need to be able to mock nested classes that have been injected using JUnit so I can create characterization tests. The problem is:

class 1 is using an object of class 2 and class 2 is using an object of class 3. And class 3 object is null when test is run on a class 1 method

this is the class structure I have:

class 1 {
    @Inject private Class2  class2 ;
}

class 2 {
    @Inject private Class3  class3 ;
}

my test suite needs to run from the top down in order to fully test my system as it is an old system and I need to write tests starting from the top in order to gradually refactor it.

Test suite:

@RunWith(MockitoJUnitRunner.class)
public class Class1Test {
    @Mock
    Class3 class3;//this doesn't work object remains null inside of mocked class2

    @Mock
    Class2 class2; //this injection works and the object isn't null inside of class1

    @InjectMocks
    public Class1 class1;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }
    @Test 
public void testFunction()
{
assertNotNull(class1.exampleFunction());
}

}

I know the correct way is to stub dependencies, but this codebase is far too large to have to write unit tests for every layer, I need to be able to write tests in JUnit so that way I can run these tests while refactoring the codebase to make sure I haven't broken anything, hence why I haven't used postman since I need it to be quick.

on java 8 @inject is a java annotation using JUnit 4 but I think I can use junit5 if I need to. the project is a j2ee (java ee ) application

1 answer

  • answered 2021-03-03 05:39 Praveen Kumar

    If I understood the problem correctly, class 1 is using an object of class 2 and class 2 is using an object of class 1. And class 3 object is null when test is run on a class 1 method.

    You can use deep stubbing for class 2.

    @Mock(answers=Answers.RETURNS_DEEP_STUBS)
    Class class2;