How to use @InjectMocks with Mockito - Tutorial

แชร์
ฝัง
  • เผยแพร่เมื่อ 7 ก.ค. 2024
  • Learn about how you can use @InjectMocks to automatically add services to classes as they are tested with Mockito.
    @InjectMocks will allow you to inject other spies and mocks into a class that requires services when it is being tested. The annotation will scan the class under test and automatically inject all available mocks and spies from within the test class. No more NullPointerExceptions when an unknown service is called!
    Link to source code: github.com/4neesh/TH-cam-Cha...
    Comment, like and subscribe for more content on Java and software engineering.
    Visit my website to also see my blogs: aneesh.co.uk​
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 16

  • @semharweldegiorgis8090
    @semharweldegiorgis8090 2 ปีที่แล้ว +2

    Very well explained. Exactly what I was looking. Thank you!!

    • @AneeshMistry
      @AneeshMistry  2 ปีที่แล้ว

      Thanks Semhar!

    • @dm1tryr905
      @dm1tryr905 8 หลายเดือนก่อน

      @@AneeshMistry GETVegetarianBreakfest()

  • @akshayrc
    @akshayrc 2 ปีที่แล้ว

    This was helpful!

  • @vlaskz
    @vlaskz ปีที่แล้ว

    Fantastic!

  • @pguti778
    @pguti778 ปีที่แล้ว

    Great video!! I'll subscribe!!!

  • @akshaysilgari2097
    @akshaysilgari2097 ปีที่แล้ว +1

    Good explanation...

  • @amrutafolane3040
    @amrutafolane3040 ปีที่แล้ว

    Great Tutorial!
    Two questions:
    1) Why did you choose `@Spy` over `@Mock` for the mocked classes?
    2) How to implement mocks if I have another custom logger class inside of BreakfastWaiter and DinnerWaiter classes? In that case, it will be a mock inside mock, Ive tried just mocking the BreakfastWaiter for example, but when I call the method in its CustomLogger class, it would throw a NullPointer. How to tackle that case?

  • @soumyadebbasu7882
    @soumyadebbasu7882 ปีที่แล้ว

    Can we also annotate the two breakfast and dinner services with @Autowired annotation? If we do not use constructor or setters ?

    • @AneeshMistry
      @AneeshMistry  ปีที่แล้ว +1

      Yes, inject mocks works the exact same way. No need to make any changes to the test, the injected classes will be automatically picked up

  • @takalanimufamadi1368
    @takalanimufamadi1368 2 ปีที่แล้ว

    I get a null pointer exception when I implement this. It says that " this.customerOrder is null ".

    • @AneeshMistry
      @AneeshMistry  2 ปีที่แล้ว

      Hi Takalani, please can you share the link to the src code? Are you annotating the class with MockitoJUnitRunner.class?