Mockito - NullpointerException when stubbing Method

后端 未结 18 1589
半阙折子戏
半阙折子戏 2020-11-30 20:54

So I started writing tests for our Java-Spring-project.

What I use is JUnit and Mockito. It\'s said, that when I use the when()...thenReturn() option I can mock ser

18条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 21:26

    For future readers, another cause for NPE when using mocks is forgetting to initialize the mocks like so:

    @Mock
    SomeMock someMock;
    
    @InjectMocks
    SomeService someService;
    
    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this); //without this you will get NPE
    }
    
    @Test
    public void someTest(){
        Mockito.when(someMock.someMethod()).thenReturn("some result");
       // ...
    }
    

    Also make sure you are using JUnit for all annotations. I once accidently created a test with @Test from testNG so the @Before didn't work with it (in testNG the annotation is @BeforeTest)

提交回复
热议问题