0

I am using spring boot 1.4,

when using the @SpringBootTest annotation for integration test, it gives a null pointer.

@RunWith(SpringRunner.class);
@SpringBootTest
public class MyControllerTest {
  @Test
  public void mytest {
     when().
            get("/hello").
     then().
            body("hello");
  }
}

and for main class:

@SpringApplication
@EnableCaching
@EnableAsync
public class HelloApp extends AsyncConfigureSupport {
  public static void main(String[] args) {
     SpringApplication.run(HelloApp.class, args);
  }

  @Override
  public Executor getAsyncExecutor() {
    ...
  }
}

Then in my controller:

@RestController
public class HelloController {
  @Autowired
  private HelloService helloService;

  @RequestMapping("/hello");
  public String hello() {
    return helloService.sayHello();
  }
}

HelloService

@Service
public class HelloService {
  public String sayHello() {
    return "hello";
  }
}

But it ways says NullPointException when for helloService when processing request.

What am I missing?

Jakim
  • 1,713
  • 7
  • 20
  • 44
  • how does your package structure look like? i.e can spring find your application configuration? – epoch Apr 07 '17 at 09:33

2 Answers2

0

You need to mock HelloService in your test class as your controller is calling a service .Here in your case Your Test class is not aware that there is any service available or not

Rahul Anand
  • 165
  • 7
  • While this might be a valuable hint to solve the problem, a good answer also demonstrates the solution. Please [edit] to provide example code to show what you mean. Alternatively, consider writing this as a comment instead. – Toby Speight Apr 07 '17 at 10:38
  • Thanks for the answer, I don't think I need to mock HelloService, my understanding is MockMvc gives a mock servlet environment, not my whole application. If I need to mock the service, why I need integration test? because the service is fake, what's the point of testing? please correct me my understanding is wrong. – Jakim Apr 09 '17 at 08:58
0

The following example test class might help you. In this guide from spring an example is shown how to integration test a rest controller in a spring fashion way.

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class HelloControllerTest {

    private MockMvc mockMvc;
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        this.mockMvc =  MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void hello() throws Exception {
        mockMvc.perform(get("/hello")).andExpect(content().string("hello"));    
    }
}
Sander_M
  • 1,109
  • 2
  • 18
  • 36