logger
logger

Reputation: 2053

How do I test with injected class? Junit return NPE

I have a simple service like below

@Service
public class MyService {
   @Inject SomeClass someClass;

   public resp doSomething(){
     return someclass.executeSomething();
   }
}

And here is my test:

public class SomeServiceTest {
   @Mock
   SomeClass someClass;

   MyService myService;

   @Before
   public setUp() {
      myService = new MyService();
   }

   @Test
   public void testExecute() {
      Resp resp = myService.doSomething();
      assertNotNull(resp);
   }
}

I am getting nullpointer exception when pointed at someclass.executeSomething(); where someclass is null. How do I mock the injected class?

Upvotes: 0

Views: 553

Answers (1)

olz
olz

Reputation: 136

Like suggested in my previous comment, like this should do the trick.

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
   @Mock
   SomeClass someClass;
   @InjectMocks
   MyService myService;
  
   @Test
   public void testExecute() {
      Resp resp = myService.doSomething();
      assertNotNull(resp);
   }
}

Upvotes: 2

Related Questions