Mohit H
Mohit H

Reputation: 959

Mocking with @mock is coming as null

I am trying to run a junit test like this , using mockito and injecting dependancies in the PageBuilderService service class .

  @RunWith(MockitoJUnitRunner.class)
  @ActiveProfiles(profiles = "staging")
  @ContextConfiguration(loader = AnnotationConfigContextLoader.class , classes = {ContentProperties.class , MasterPropertiesFactory.class })
  class PageBuilderServiceTest {



      @Mock
      public CService cs;

      @Mock
      private RService rs;

      @InjectMocks
      PageBuilderService pageBuilderService  ;




      @ParameterizedTest
      @EnumSource(HompageEnum.class)
      @DisplayName("Testing doIt wsith EnumSource")
      public void checkRowposition(HompageEnum homepageEnum) {

          Mockito.when(contentProperties.getPageFolder(anyString())).thenReturn("http://google.com");


      }

  }

My Main class is

    @Service("pgService")
    public class PageBuilderService {


        @Autowired
        private RService rs;

        @Autowired
        public CService cs;



        public Queue<String> getPaginatedContent(HomepageRequest homepageRequest) {

            Queue<String> staticContent = getStaticContent(homepageRequest.getUrl());

            return staticContent
        }



        public Queue<String> getStaticContent(String url) {

            Queue<String> files = new LinkedList<>();

            String dir = contentProperties.getPageFolder(url);


            return null;
        }


    }

When we do ContentProperties content = mock(ContentProperties.class) , it works fine but contentProperties is coming as null when i use mock Annotation .

Upvotes: 0

Views: 255

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42441

I don't see what is contentProperties - you don't inject it in the test, but here is one thing that is clearly wrong:

If you want to start spring you have to run it with SpringJUnit4ClassRunner.class / SpringRunner.class and not with mockito runner.

Without spring runner, there is no point in specifying:

@ActiveProfiles(profiles = "staging")
  @ContextConfiguration(loader = AnnotationConfigContextLoader.class , classes = {ContentProperties.class , MasterPropertiesFactory.class })

Other than that, please check that @Mock public CService cs; and other fields annotated with @Mock do have value (its basically what Mockito runner is supposed to do, so unless something is missing here, there is no difference between other mocks and contentProperties)

Upvotes: 1

Related Questions