我正在使用spring boot 1.4,
使用@SpringBootTest注释进行集成测试时,它会给出一个空指针。
@RunWith(SpringRunner.class);
@SpringBootTest
public class MyControllerTest {
@Test
public void mytest {
when().
get("/hello").
then().
body("hello");
}
}
和主要课程:
@SpringApplication
@EnableCaching
@EnableAsync
public class HelloApp extends AsyncConfigureSupport {
public static void main(String[] args) {
SpringApplication.run(HelloApp.class, args);
}
@Override
public Executor getAsyncExecutor() {
...
}
}
然后在我的控制器中:
@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";
}
}
但是当处理请求时,对于helloService,它会说NullPointException。
我错过了什么?
答案 0 :(得分:0)
您需要在测试类中模拟HelloService,因为您的控制器正在调用服务。在您的情况下,您的测试类不知道有任何可用的服务
答案 1 :(得分:0)
以下示例测试类可能对您有所帮助。在本指南from spring中,展示了如何以弹簧方式集成测试其余控制器的示例。
@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"));
}
}