I'm writing test for rest app in spring boot.
But in my test, interface CategoryService in CategoryController cannot be autowired when running test and NullPointerException raised.
CategoryService is injected at field level.
Here my classes:
CategoryController
@RestController
@RequestMapping("/v1/categories")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@RequestMapping
public List<Category> getAll() {
return categoryService.findAll();
}
}
CategoryService
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
CategoryRepository categoryRepository;
@Override
public List<Category> findAll() {
return categoryRepository.findAll();
}
}
CategoryRepositoryImpl
@Repository
public class CategoryRepositoryImpl implements CategoryRepository {
@Override
public List<Category> findAll() {
...
}
}
----- TEST ------
AppTestConfig
@Configuration
public class AppTestConfig {
@Bean
public CategoryRepository categoryRepository() {
return new TestCategoryRepository();
}
@Bean
public CategoryService categoryService() {
return new App.CategoryServiceImpl();
}
}
CategoryControllerTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppTestConfig.class})
public class CategoryControllerTest {
@Autowired
private CategoryRepository categoryRepository;
@Test
public void testGetAll() throws Exception {
CategoryController controller = new CategoryController();
List<Category> categories = controller.getAll();
assertEquals(categoryRepository.findAll().size(), categories.size());
}
}
With constructor injection, everything works fine.
What's the problem?