I have the following entity class that before creating an object should call the getUniqueSlug
method to check if there are already items with the same name.
@Entity public class Category {
@Column private Long id;
@Column(nullable = false) private String name;
@Column(nullable = false) private String slug;
@Autowired private CategoryRepository categoryRepository;
public String getUniqueSlug(String name) {
int i = 1;
while (this.categoryRepository.findBySlug(Slug.toSlug(name)) != null) {
name = name + " " + i;
i++;
}
return Slug.toSlug(name);
}
// Constructors
public Category() {
}
public Category(String name) {
this.name = name;
this.slug = getUniqueSlug(name);
}
// Getters and setters
I also have the following test to check if it does it properly:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration public class CategoryTest {
private MockMvc mockMvc;
@Autowired private CategoryRepository categoryRepository;
@Autowired ObjectMapper objectMapper;
@Autowired private WebApplicationContext webApplicationContext;
@Before public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
this.categoryRepository.deleteAll();
this.categoryRepository.save(new Category("My category name"));
}
@Test public void testUniqueSlug() throws Exception {
String slug = "My category name";
int integer = 1;
while (categoryRepository.findBySlug(Slug.toSlug(slug)) != null) {
slug = slug + " " + integer;
integer++;
}
this.categoryRepository.save(new Category(slug));
System.out.println(this.categoryRepository.findAll());
}
When I run that test, I get the NullPointerException
, so I assume that the problem is somewhere in autowiring the repository in the Category
class. Where exactly?