简体   繁体   中英

Mockito injected mock is null

I want to test a service class which extends an abstract class using Mockito. My code looks like following:

    public abstract class MyFooServiceAbstractClass {
       @Autowired
       private FooRepository fooRepository;
   
       public save(FooEntity foo){fooRepository.save(foo);}
   }
   
   @Service
   public class FooService extends MyFooServiceAbstractClass {
      private final BarService barService;

      public FooService(BarService barservice){
         this.barService = barservice;
      }

      public void create(FooEntity fooEntity){
        barService.returnSomething();
        save(fooEntity);
      }
    }

Concerting the test, I am using MockitoEntension. the test is as following:

@ExtendWith(MockitoExtension.class)
public class FooServiceTest {
  @InjectMocks
  private FooService fooService;
  @Mock
  private FooRepository fooRepository;
  @Mock
  private BarService barService;
  @Captor
  private ArgumentCaptor<FooEntity> captor;

   @Test
   void test(){
     // Given
     FooEntity foo = new FooEntity();
     when(barService.doSomething()).thenReturn(something);
     
     // When
     fooService.save(foo);

     // Then
     verify(fooRepository).save(captor.capture());
     
     // assert goes here...
  }
}

When debuging the test, fooRepository is null.

By changing the injection in FooService from constructor injection to Autowired, the mock fooRepository stops being null.

Using Autowired and constructor injections seems to be working fine when the spring context is created.

My question is: What is the difference between creating the mocks in mockito and creating the real beans?

From the given code above, I can see that the constructor for FooService does not accept an object for FooRepository. Can you please try the code in the following format? (since you mentioned using Lombok, I have used lombok annotations)

    @RequiredArgsConstructor
    public abstract class MyFooServiceAbstractClass {
       private final FooRepository fooRepository;
   
       public save(FooEntity foo){fooRepository.save(foo);}
   }
   
   @Service
   public class FooService extends MyFooServiceAbstractClass {
      private final BarService barService;

      public FooService(BarService barservice, FooRepository fooRepository){
         super(fooRepository)
         this.barService = barservice;
      }

      public void create(FooEntity fooEntity){
        barService.returnSomething();
        save(fooEntity);
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM