NullPointerExecption on mocked @Repository object in SpringBoot Project

24 Views Asked by At

I have a class Logic.java which is defined as:

@Component
public class Logic{

    @Autowired
    @Lazy
    OptionRepo optionRepo;

    @Autowired
    @Lazy
    Status status;


    public Set<String> getOptions(String str1, String str2, List<Object> objects){
        optionRepo.getOptions(str1, str2, objects).forEach(option -> objects.stream() // Some code );
    }

}

@Repository
public class OptionRepo{
    public List<String> getOptions(String str1, String str2, List<Object> objects);
}

Now, I have Test.java class.

@SpringBootTest
public class Test{
    @Mock
    OptionRepo optionRepo;  // --> Not working

    //@MockBean 
    //OptionRepo optionRepo;   // --> Not working

    @Mock
    Status status;

    @Test
    public void testMethod(){
        String str1 = "str1";
        String str2 = "str2";
        Object obj = new Object();

        Mockito.when(optionRepo).getOptions(str1, str2, List.of(obj)).thenReturn(Some Set of String);  // --> Not working

        when(optionRepo.getOptions()).thenReturn(Some Set of String); // --> Not working

        when(status.getStatus()).thenReturn(status String);  // --> works Well!
        
    }
}

At runtime, I get optionRepo as null. None of the above mocking options work. But, @Repository class Status.java works fine.

I don't know why OptionRepo's mocked bean doesn't work. But mocked Status.java bean works.

0

There are 0 best solutions below