One of my Spring boot controller method calls a static method. I want to test the controller using powermokito. Find below the code for the same. I'm getting an error when im trying call the mockMvc.perform() method @RunWith(PowerMockRunner.class)
@PrepareForTest({StaticClass.class})
public void StaticClassTests()
{
@Autowired
private MockMvc mockMvc;
@Test
public void testStatic()
{
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
PowerMokito.when(StaticClass.getList()).thenReturn(list);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/getlist")
.accept(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder) //where the error is
.andExpect(status().isOk())
.andExpect(content().json("[\n" +
" \"a\",\n" +
" \"b\",\n" +
" \"c\"\n" +
"]"))
.andReturn();
}
}
StaticClass.getList() is a static method Im getting java.lang.NullPointerException at the commented line( i.e mockMvc.perform(requestBuilder))
You should initialize mockMvc before calling perform method.
// Setup Spring test in standalone mode
this.mockMvc = MockMvcBuilders.standaloneSetup(carSearchController).build();
Note: Inject your controller as here did for the CarSearchController
@InjectMocks
private CarSearchController carSearchController;