我正在测试一个简单的初学者 Spring Boot 应用程序,但它不断为我的服务类和我的存储库类抛出。这是我的控制器类:NullPointerException@EnableAutoConfiguration@RestControllerpublic class MyController { @Autowired private MyService service; @GetMapping("/welcome") public String home throws IOException { return service.getEntities(); }}这是服务类:@EnableAutoConfiguration@Servicepublic class MyService{@Autowired(required=true)private MyRepository repository;public MyService() {};public List<Entity> getEntities() throws IOException { return repository.findAll(); }这是存储库:@Repositorypublic 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")@EnableAutoConfigurationpublic 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();
1 回答
HUH函数
TA贡献1836条经验 获得超4个赞
您使用 in line 创建了 MyController:new
private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController()).build();
春天可能没有注入它。尝试自动布线:Service
@Autowired
private MyController myController;
并将实例化移动到方法:MockMvc@Before
private MockMvc mvc;
@Before
public void initialize() {
mvc = MockMvcBuilders.standaloneSetup(myController).build();
}
添加回答
举报
0/150
提交
取消