These are service and repository classes which i am trying to test.
#Service
public class BookServiceImpl implements BookService {
#Autowired
private BookRepository bookRepository;
#Override
public List<Book> getAllBooks() {
return bookRepository.getAllBooks();
}
#Override
public Book getBookById(int productID) {
return bookRepository.getBookById(productID);
}
#Override
public List<Book> getBookByCategory(String category) {
return bookRepository.getBookByCategory(category);
}
#Override
public Set<Book> getBooksByFilter(Map<String, List<String>> filterParams) {
return bookRepository.getBooksByFilter(filterParams);
}
}
#Repository
#Configuration
public class InMemoryBookRepository implements BookRepository {
private List<Book> listOfProducts = new ArrayList<Book>();
public InMemoryBookRepository() {
Book algorithms = new Book(1, "Book", "Book", 29);
algorithms.setDescription("description.");
algorithms.setCondition("Available");
algorithms.setUnitsInStock(4);
algorithms.setCategory("java");
algorithms.setManufacturer("Nenov");
listOfProducts.add(algorithms);
Book book2 = new Book(2, "Thinking in Java", "Bruce Ekel", 5352);
book2.setDescription("Description");
book2.setCondition("Available");
book2.setUnitsInStock(100);
book2.setCategory("programming");
book2.setManufacturer("Nikola");
listOfProducts.add(book2);
}
#Override
public List<Book> getAllBooks() {
return listOfProducts;
}
#Override
public Book getBookById(int bookId) {
Book bookById = null;
for (Book book : listOfProducts) {
if (book != null && book.getId() != 0) {
bookById = book;
break;
}
}
return bookById;
}
#Override
public List<Book> getBookByCategory(String category) {
List<Book> productsByCategory = new ArrayList<Book>();
for (Book book : listOfProducts) {
if (category.equalsIgnoreCase(book.getCategory())) {
productsByCategory.add(book);
}
}
return productsByCategory;
}
#Override
public Set<Book> getBooksByFilter(Map<String, List<String>> filterParams) {
Set<Book> productsByBrand = new HashSet<Book>();
Set<Book> productsByCategory = new HashSet<Book>();
Set<String> criterias = filterParams.keySet();
if (criterias.contains("brand")) {
for (String brandName : filterParams.get("brand")) {
for (Book book : listOfProducts) {
if (brandName.equalsIgnoreCase(book.getManufacturer())) {
productsByBrand.add(book);
}
}
}
}
if (criterias.contains("category")) {
for (String category : filterParams.get("category")) {
productsByCategory.addAll(this.getBookByCategory(category));
}
}
productsByCategory.retainAll(productsByBrand);
return productsByCategory;
}
}
I am trying to make unit test on service but a have null pointer exception. I hope someone will help. If you need more code please notify me.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({ "Context.xml" })
public class BookServiceTest {
#Mock
private BookRepository bookRepository;
#Test
public void testGetBookById() {
Book book = new Book(1, "Book", "Book", 29);
int id = book.getId();
assertNotNull("Object can not have null id ", id);
Book searchedBook = bookRepository.getBookById(id); // nullpointer here !
assertNotNull("Book should be found ", searchedBook);
assertTrue("Found book id should be equal to id being searched", searchedBook.getId() == 1);
}
}
Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="bookRepository" name="bookRepository" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg value="com.book.contracts.BookRepository" />
</bean>
</beans>
Stack trace:
java.lang.NullPointerException
at store.BookServiceTest.testGetBookById(BookServiceTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
StackTrace with #Autowired
java.lang.AssertionError: Book should be found
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertNotNull(Assert.java:712)
at store.BookServiceTest.testGetBookById(BookServiceTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
EDIT:
#Test
public void testGetBookById() {
Book book = new Book(1, "Book", "Book", 29);
int id = book.getId();
assertNotNull("Object can not have null id ", id);
Book searchedBook = bookRepository.getBookById(id);
Assertions.assertThat( searchedBook ).isNotNull();
assertTrue("Found book id should be equal to id being searched", searchedBook.getId() == 1);
}
Stacktrace
java.lang.AssertionError: expecting actual value not to be null
at org.fest.assertions.Fail.failure(Fail.java:228)
at org.fest.assertions.Fail.fail(Fail.java:167)
at org.fest.assertions.Fail.failIfActualIsNull(Fail.java:100)
at org.fest.assertions.GenericAssert.isNotNull(GenericAssert.java:238)
at store.BookServiceTest.testGetBookById(BookServiceTest.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
After you initialize your own context with Spring you don't have to type put #Mock annotation. Just put #Autowired and you are fine to go.
#Autowired
private BookRepository bookRepository;
After you put #Autowired I suggest you to use fest.assertions class such as:
Assertions.assertThat( myBook ).isNotNull();
And the import is:
import org.fest.assertions.Assertions;
Edit: Since you are using java.lang assertions, you will always get exceptions.
The meaning of an AssertionError is that something happened that the
developer thought was impossible to happen.
So if an AssertionError is ever thrown, it is a clear sign of a
programming error.
So you have to look forward for http://mvnrepository.com/artifact/org.easytesting/fest-assert if you are using maven, otherwise download it as jar and add it to your dependencies. Then you can use my suggestion.
Related
I'm trying to test a method in service class which uses ModelMapper to convert entity to dto, but I'm getting NullPointerException at this line mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); in the service class.
Exception
java.lang.NullPointerException
at pro.budthapa.service.impl.StockCategoryServiceImpl.getStockCategoryByIdAndBusinessGroupId(StockCategoryServiceImpl.java:56)
at pro.budthapa.service.impl.StockCategoryServiceImplTest.WhenCategoryPresent_ShouldReturnCategory(StockCategoryServiceImplTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Test Class
#RunWith(MockitoJUnitRunner.class)
public class StockCategoryServiceImplTest {
#Mock
private ModelMapper mapper;
#Mock
private StockCategoryRepository stockCategoryRepository;
#InjectMocks
private StockCategoryServiceImpl stockCategoryService;
#Before
public void setup() {
mapper = new ModelMapper();
}
#Test
public void WhenCategoryPresent_ShouldReturnCategory() throws Exception {
int bgId = 10;
int categoryId = 5;
StockCategory sc = new StockCategory();
sc.setCategoryId(categoryId);
sc.setBusinessGroupId(String.valueOf(bgId));
sc.setDescription("Test Item");
Mockito.when(stockCategoryRepository.findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId))).thenReturn(Optional.of(sc));
StockCategoryDto result = stockCategoryService.getStockCategoryByIdAndBusinessGroupId(categoryId, bgId);
assertEquals(5, result.getCategoryId() );
assertEquals(10, result.getBusinessGroupId());
assertNotNull(result.getDescription());
Mockito.verify(stockCategoryRepository, Mockito.times(1)).findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId));
}
}
Service Class
#Service
public class StockCategoryServiceImpl implements StockCategoryService {
private ModelMapper mapper;
private StockCategoryRepository stockCategoryRepository;
public StockCategoryServiceImpl(ModelMapper mapper, StockCategoryRepository stockCategoryRepository) {
this.mapper = mapper;
this.stockCategoryRepository = stockCategoryRepository;
}
#Override
public StockCategoryDto getStockCategoryByIdAndBusinessGroupId(int categoryId, int bgId) {
Optional<StockCategory> cat = stockCategoryRepository.findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId));
if(cat.isPresent()) {
//getting NullPointerException at this line
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
return mapper.map(cat.get(), StockCategoryDto.class);
}
StockCategoryDto dto = new StockCategoryDto();
dto.setMessage("Category not found for given id: "+categoryId);
return dto;
}
}
You shouldn't reassign your mocked ModelMapper in setup method. Remove this method
And I can't find in your code mock definition for mapper.getConfiguration()
when(mapper.getConfiguration()).thenReturn(...)
You should tell it to mockito.
I cannot pass test notFoundFoo since I get NestedServletException excpetion instead of expected FooNotFoundException exception.
What I do wrong in my test?
Controller:
#RestController
#RequestMapping("/api/foo")
public class FooController {
#Autowired
private FooService fooService;
#GetMapping("/{fooId}/status")
#ResponseStatus(HttpStatus.OK)
public PaymentStatus retrievePaymentStatus(#PathVariable String fooId) {
PaymentStatus paymentStatus = fooService.retrievePaymentStatus(fooId);
if (paymentStatus == null) {
throw new InvoiceNotFoundException();
}
// Preconditions.checkNotNull(paymentStatus, new FooNotFoundException());
return paymentStatus;
}
}
FooNotFoundException:
#ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Foo not found")
public class FooNotFoundException extends RuntimeException {
public FooNotFoundException() {
}
public FooNotFoundException(String message) {
super(message);
}
}
Tests:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = App.class)
#AutoConfigureMockMvc
public class FooControllerTest {
#Autowired
FooRepository fooRepository;
#Autowired
BloomFilterManager bloomFilterManager;
#Autowired
private MockMvc mockMvc;
private MediaType CONTENT_TYPE = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
#Test
public void foundFooWithPaymentStatus() throws Exception {
Faker faker = new Faker();
Foo.PaymentStatus[] paymentStatuses = Foo.PaymentStatus.values();
Foo foo= fooRepository.save(new Foo(
faker.number().randomNumber(),
faker.lorem().word(),
faker.number().randomDigit(),
new BigDecimal(Math.random()),
paymentStatuses[faker.number().numberBetween(0, paymentStatuses.length)],
faker.date().between(new Date(), DateUtils.addDays(new Date(), 13))
));
bloomFilterManager.getBloomFilter().put(foo.getId());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get("/api/foo/{fooId}/status", foo.getId())
.accept(CONTENT_TYPE);
MvcResult result = mockMvc.perform(requestBuilder)
.andExpect(status().isOk())
.andExpect(content().contentType(CONTENT_TYPE))
.andReturn();
String expected = "\"" + foo.getPaymentStatus() + "\"";
assertEquals(expected, result.getResponse().getContentAsString());
}
#Test(expected = FooNotFoundException.class)
public void notFoundFoo() throws Exception {
String fooId = "100000000000000";
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get("/api/foo/{fooId}/status", fooId)
.accept(CONTENT_TYPE);
mockMvc.perform(requestBuilder)
.andExpect(status().isNotFound())
.andExpect(content().contentType(CONTENT_TYPE));
}
Output:
java.lang.Exception: Unexpected exception, expected<org.learn.foo.exception.FooNotFoundException> but was<org.springframework.web.util.NestedServletException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException: org.learn.foo.exception.FooNotFoundException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at org.learn.integration.FooControllerTest.notFoundFoo(FooControllerTest.java:100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
... 28 more
Caused by: java.lang.NullPointerException: org.learn.foo.exception.FooNotFoundException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:900)
at org.learn.foo.controller.FooController.retrievePaymentStatus(FooController.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 58 more
UPDATED:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/foo/100000000000000/status
Parameters = {}
Headers = {Accept=[application/json;charset=UTF-8]}
Handler:
Type = org.wixanz.omniva.foo.controller.FooController
Method = public org.wixanz.omniva.foo.domain.foo$PaymentStatus org.wixanz.omniva.foo.controller.FooController.retrievePaymentStatus(java.lang.String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.wixanz.omniva.foo.exception.InvoiceNotFoundException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = Foo not found
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.Exception: Unexpected exception, expected<org.wixanz.omniva.foo.exception.FooNotFoundException> but was<java.lang.AssertionError>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.AssertionError: Content type not set
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:35)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:65)
at org.springframework.test.web.servlet.result.ContentResultMatchers$1.match(ContentResultMatchers.java:81)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at org.wixanz.omniva.integration.FooControllerTest.notFoundFoo(FooControllerTest.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
... 28 more
NestedServletException wraps only the cause of the exception.
It is not your actual issue.
Its javadoc defines itself as :
Subclass of ServletException that properly handles a root cause in
terms of message and stacktrace, just like
NestedChecked/RuntimeException does.
Exceptions thrown in a rest controller have to be mapped to a http response. If you didn't it, Spring does that for you by throwing NestedServletException/NestedCheckedException according to the exception nature (checked or runtime).
A Java exception is not a http response.
You cannot let it be thrown as you did in a classic java code.
You have to convert it as something compatible with the http norms.
For Rest controllers you should use #ExceptionHandler and #ControllerAdvice.
#ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(FooNotFoundException.class)
protected ResponseEntity<Object> handleFooNotFound(FooNotFoundException exception, WebRequest request) {
return handleExceptionInternal(exception, "Foo Not Found",
new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}
I use spring framework 4 and have class that has his line :
String link = ServletUriComponentsBuilder.fromCurrentContextPath().path("/admin/menu/edit/"+id).build().toUriString();
Class perfectly run in on server but when I want to unit test it and create the class and call method that use above could got a error:
java.lang.IllegalStateException: Could not find current request via RequestContextHolder
at org.springframework.util.Assert.state(Assert.java:392)
at org.springframework.web.servlet.support.ServletUriComponentsBuilder.getCurrentRequest(ServletUriComponentsBuilder.java:190)
at org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentContextPath(ServletUriComponentsBuilder.java:158)
at com.mohsenj.core.util.HiararchyUtils.createTableTrMenu(HiararchyUtils.java:175)
at com.mohsenj.core.util.HiararchyUtils.getHForTableMenu(HiararchyUtils.java:153)
at com.mohsenj.core.util.HiararchyUtils.getHForTableMenu(HiararchyUtils.java:158)
at com.mohsenj.core.util.HiararchyUtilsTest.getHForTableMenu_verifyReturnString(HiararchyUtilsTest.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
my class:
#Component
public class HiararchyUtils {
public String getHForTableMenu(List<? extends Hierarchically> menus, Integer parentId) {
seperateParentsIntoAssoc(menus);
return createTableTrMenu(parentId, 0);
}
public String createTableTrMenu(Integer parent, Integer level) {
// some code
String link = ServletUriComponentsBuilder.fromCurrentContextPath().path("/admin/menu/edit/"+items.get(itemId).getId()).build().toUriString();
// some code
}}
test class :
#RunWith(MockitoJUnitRunner.class)
public class HiararchyUtilsTest {
private HiararchyUtils hiararchyUtils;
#Before
public void setup() {
hiararchyUtils = new HiararchyUtils();
}
#Test
public void getHForTableMenu_() {
String trs = hiararchyUtils.getHForTableMenu(menus);
}
}
what should I do?
It may be as easy as adding a MockHttpServletRequest in order to provide the needed RequestContextHolder and context path.
As a class variable, add
private MockHttpServletRequest mockRequest;
Then, when setting up your test(s), try:
#Before
mockRequest = new MockHttpServletRequest();
mockRequest.setContextPath("/your-app-context");
ServletRequestAttributes attrs = new ServletRequestAttributes(mockRequest);
RequestContextHolder.setRequestAttributes(attrs);
That should address that error.
I would like to add caching to my Spring Boot 4 application.
As a key I would like to use id (type Long) of my entity, value is my entity.
#EnableCaching
#SpringBootApplication
public class SpringBootMainApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMainApplication.class, args);
}
}
#Configuration
public class AppConfiguration {
#Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("findOne");
}
}
public interface SampleEntityService extends CrudRepository<SampleEntity, Long> {
#Cacheable(key = "#a0", value = "findOne")
SampleEntity findOne(Long id);
}
but when I call findOne method in my test I got an exception:
java.lang.ClassCastException: org.springframework.cache.support.SimpleValueWrapper cannot be cast to my.springboot.model.SampleEntity
at my.springboot.SampleEntityCacheTest.aaa(SampleEntityCacheTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
According to some tutorials, I tried to use many variants, but all of them fail.
#Cacheable(key = "#a0", value = "findOne")
#Cacheable(key = "#p0", value = "findOne")
#Cacheable(key = "a0", value = "findOne")
#Cacheable(key = "p0", value = "findOne")
#Cacheable(key = "#id", value = "findOne")
#Cacheable(key = "id", value = "findOne")
#Cacheable(key = "#root.id", value = "findOne")
#Cacheable(key = "root.id", value = "findOne")
What do I do wrong ?
======= answer =========
Proper solution is:
#Cacheable(key = "#a0", value = "findOne")
and inside the test I should have done something like that:
#Test
public void aaa() {
SampleEntity entity = sampleEntityService.save(create("name1", uuid(1)));
sampleEntityService.findOne(entity.getId());
SampleEntity entityFromCache =(SampleEntity) cacheManager.getCache("findOne").get(entity.getId()).get();
assertNotNull(entityFromCache);
}
An issue has appeared for our code after updating to SDN4:
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.server.model.neo4j.node.Item
at com.example.server.service.relationship.friend.FriendRelationshipService.getSkillUuidByPotentialSkillName (FriendRelationshipService.java:257)
at com.example.server.service.relationship.friend.FriendRelationshipService.createFriendRequestRelationshipBetweenPeople(FriendRelationshipService.java:211)
at com.example.server.service.relationship.friend.FriendRelationshipService.sendFriendRequestHelper(FriendRelationshipService.java:171)
at com.example.server.service.relationship.friend.FriendRelationshipService.sendFriendRequest(FriendRelationshipService.java:81)
at com.example.server.test.integration.controller.api.friends.TestLoadFriendRequestsBothWays.testLoadFriendRequestsBothWaysNullCommonSkillNameSupplied(TestLoadFriendRequestsBothWays.java:184)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:85)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:86)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:243)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:182)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
The code that causes the exception is below:
Iterable<Item> items = itemRepository.findItemsByPerson(person.getUuid(), new Pagination(0, 1));
for(Item item : items) { // Stacktrace leads the issue to here.
currItem = item;
break;
}
Perhaps this is something to do with the for-each loop, as this appears to be the case for other parts of the code which also shows this issue.
Update 05/08/2015: The Item class is as below:
#NodeEntity
public class Item extends Entity implements Packageable {
private String name;
private String shortDescription;
private boolean isUserCreatedItem = false;
private double timestamp;
#Relationship(type = "CREATED_BY")
private Person creator;
public Item() {
}
/**
* This should be called after instantiating a new node (indicating a new node is to be added to the database)
*/
#Override
public void init() {
super.init();
}
// Other methods here
}
And the Entity class:
public abstract class Entity {
private String uuid;
#GraphId private Long id;
public void init() {
// generate the UUID
if(uuid == null) {
uuid = Util.generateUUID();
}
}
}
The repository query method:
#Query("MATCH (item)<-[:HAS_ITEM]-(you {uuid: {0}}) "
+ "RETURN DISTINCT item "
+ "ORDER BY item.name")
Iterable<Item> findItemsByPerson(String personUuid);
Any help would be much appreciated.
Cheers
This is a bug which you can track at https://jira.spring.io/browse/DATAGRAPH-727
As a temporary workaround, please use a Collection instead of an Iterable.