我正在测试一个简单的初学者 Spring Boot 应用程序,但它不断为我的服务类和我的存储库类抛出。
这是我的控制器类:NullPointerException
@EnableAutoConfiguration
@RestController
public class MyController {
@Autowired
private MyService service;
@GetMapping("/welcome")
public String home throws IOException {
return service.getEntities();
}
}
这是服务类:
@EnableAutoConfiguration
@Service
public class MyService{
@Autowired(required=true)
private MyRepository repository;
public MyService() {
};
public List<Entity> getEntities() throws IOException {
return repository.findAll();
}
这是存储库:
@Repository
public interface MyRepository extends JpaRepository<Entity, Long>{
List<Entity> findAll();
}
因此,如果我运行该应用程序,一切都没问题。问题是当我运行这个测试时:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { MyService.class, MyController.class, Entity.class })
@ComponentScan("test.firstproject")
@EntityScan(basePackages = {"test.firstproject.entities"})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@EnableJpaRepositories("test.firstproject.repository")
@EnableAutoConfiguration
public class TestController {
private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController).build();
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
}
}
首先,它在调用 时抛出了 NullPointerException。然后我尝试通过初始化服务来做,但这次抛出了错误。怎么了?service.getEntities()= new MyService()return repository.findAll();
HUH函数
相关分类