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.
Related
#Repository
public class ElasticRepository {
private static final Logger LOG = LoggerFactory.getLogger(ElasticRepository.class);
#Autowired
private ElasticSearchConfig elasticSearchConfig;
#Autowired
private ObjectMapper mapper;
#Autowired
private RestHighLevelClient client;
public void ingest(UnifiedOrder unifiedClubOrder) throws ElasticsearchException, JsonProcessingException {
IndexRequest indexRequest = new IndexRequest(elasticSearchConfig.elasticSearchIndex)
.id(unifiedClubOrder.getOrderNo())
.source(mapper.writeValueAsString(unifiedClubOrder), XContentType.JSON)
.version(unifiedClubOrder.getModifyTs().getTime())
.versionType(VersionType.EXTERNAL_GTE);
ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
#Override
public void onResponse(IndexResponse indexResponse) {
System.out.println("Posted Successfully in ES Index :: ");
}
#Override
public void onFailure(Exception e) {
System.out.println("Failed to post in ES Index :: ");
IndexRequest errorIndexRequest = new IndexRequest(elasticSearchConfig.elasticSearchErrorIndex)
.id(unifiedClubOrder.getOrderNo())
.source(e.getMessage(), XContentType.JSON)
.version(unifiedClubOrder.getModifyTs().getTime())
.versionType(VersionType.EXTERNAL_GTE);
ActionListener<IndexResponse> errorIndexListener = new ActionListener<IndexResponse>() {
#Override
public void onResponse(IndexResponse indexResponse) {
System.out.println("Posted Successfully in ES Error Index :: ");
}
#Override
public void onFailure(Exception e) {
System.out.println("Failed to post in ES Error Index :: ");
}
};
client.indexAsync(errorIndexRequest, RequestOptions.DEFAULT, errorIndexListener);
}
};
client.indexAsync(indexRequest, RequestOptions.DEFAULT, listener);
}
}
==================================================================================
#RunWith(MockitoJUnitRunner.class)
#PrepareForTest({RestHighLevelClient.class})
public class ElasticRepositoryTest {
#Mock
private RestHighLevelClient client;
#Mock
private ObjectMapper objectMapper;
#Mock
private ElasticSearchConfig elasticSearchConfig;
#InjectMocks
private ElasticRepository elasticRepository;
#Test
public void ingest_Test() throws Exception {
UnifiedOrder unifiedClubOrder = new UnifiedOrder();
unifiedClubOrder.setOrderNo("12345");
unifiedClubOrder.setStatus("purchase");
unifiedClubOrder.setModifyTs(new Date());
when(objectMapper.writeValueAsString(unifiedClubOrder)).thenReturn(new ObjectMapper().writeValueAsString(unifiedClubOrder));
elasticSearchConfig.elasticSearchIndex = "test";
IndexRequest indexRequest = new IndexRequest(elasticSearchConfig.elasticSearchIndex)
.id(unifiedClubOrder.getOrderNo())
.source(objectMapper.writeValueAsString(unifiedClubOrder), XContentType.JSON)
.version(unifiedClubOrder.getModifyTs().getTime())
.versionType(VersionType.EXTERNAL_GTE);
PowerMockito.whenNew(IndexRequest.class).withAnyArguments().thenReturn(indexRequest);
ArgumentCaptor<IndexRequest> argumentCaptorIndexRequest = ArgumentCaptor.forClass(IndexRequest.class);
PowerMockito.doNothing().when(client).indexAsync(Mockito.any(), Mockito.any(),
Mockito.any());
elasticRepository.ingest(unifiedClubOrder);
verify(client).indexAsync(argumentCaptorIndexRequest.capture(), Mockito.any(), Mockito.any());
assertTrue(argumentCaptorIndexRequest.getValue() instanceof IndexRequest);
assertEquals("12345", ((IndexRequest) argumentCaptorIndexRequest.getValue()));
}
}
===========================================================================================
===============Detailed Exception are below =====================================
java.lang.NullPointerException
at org.elasticsearch.client.RestHighLevelClient.performRequestAsync(RestHighLevelClient.java:1525)
at org.elasticsearch.client.RestHighLevelClient.performRequestAsyncAndParseEntity(RestHighLevelClient.java:1498)
at org.elasticsearch.client.RestHighLevelClient.indexAsync(RestHighLevelClient.java:832)
at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
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.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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
==================================================================================================
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:81)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
at org.mockito.internal.runners.DefaultInternalRunner$1$1.testFinished(DefaultInternalRunner.java:70)
at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56)
at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190)
at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72)
at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187)
at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331)
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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Adding #PowerMockIgnore({"javax.net.ssl.*"}) annotation to your Test method will ignore above exception.
I have started implementing Swagger with version 2.9.2 recently. It worked well without Jackson in other project but as I added same code with Jackson dependency my integration tests were started failing due to not able to covert it(XML string) into Json object.
Tried with different versions of Jackson data format and swagger.
My DTO class:
#Data
#AllArgsConstructor
#NoArgsConstructor
#Wither
public class PartsInfoDTO {
// TODO: 08/10/18 This class should be removed after lexcom start giving remark_line instead of RemarkLine for ex.
#JsonProperty("illustration")
private String Illustration;
#JsonProperty("quantity")
private String Quantity;
#JsonProperty("price")
private Price Price;
#JsonProperty("remark_line")
private String remarkLine;
#JsonProperty("part_number")
#ApiModelProperty(name = "part_number")
private String partNumber;
#JsonProperty("denomination_line")
private String[] denominationLine;
public PartsInfoDTO(PartsInfo partsInfo) {
setDenominationLine(partsInfo.getDenominationLine());
setIllustration(partsInfo.getIllustration());
setPartNumber(partsInfo.getPartNumber());
setPrice(partsInfo.getPrice());
setQuantity(partsInfo.getQuantity());
setRemarkLine(partsInfo.getRemarkLine());
}
}
My Swagger config:
#Configuration
#EnableSwagger2
public class PartsSwaggerConfiguration extends WebMvcConfigurationSupport {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.package.example"))
.paths(regex(PART_INFO_API))
.build();
}
}
Error with stacktrace:
com.fasterxml.jackson.core.JsonParseException: Unexpected character
('<' (code 60)): expected a valid value (number, String, array,
object, 'true', 'false' or 'null') at [Source:
(String)"1121-123453
1INR2ASWS03G102354Drucr";
line: 1, column: 2]
at
com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
at
com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:669)
at
com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:567)
at
com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddValue(ReaderBasedJsonParser.java:1894)
at
com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:749)
at
com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4141)
at
com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4000)
at
com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
at
com.vwits.asid.etka.PartInfoControllerTest.getPartInfo(PartInfoControllerTest.java:347)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at
org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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
com.github.tomakehurst.wiremock.junit.WireMockClassRule$1.evaluate(WireMockClassRule.java:60)
at org.junit.rules.RunRules.evaluate(RunRules.java:20) 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:251)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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
com.github.tomakehurst.wiremock.junit.WireMockClassRule$1.evaluate(WireMockClassRule.java:70)
at org.junit.rules.RunRules.evaluate(RunRules.java:20) at
org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
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)
I'm writing a test that calls a method from another service:
// Setup mocks
private GoalService goalService;
private Principal principal;
private Goal goal;
private SecurityService securityService;
#Before
public void setup() {
goalService = new GoalService();
principal = mock(Principal.class);
goal = mock(Goal.class);
securityService = mock(SecurityService.class, Mockito.RETURNS_DEEP_STUBS);
}
#Test
public void testRequesterOwnsGoalIsTrue() {
doReturn(1).when(securityService).getUserIdByPrincipal(principal);
when(goal.getUsersUserId()).thenReturn(1);
boolean userOwnsGoal = goalService.requesterOwnsGoal(principal, goal);
assertEquals(true, userOwnsGoal);
}
During debug, when I call securityService.getUserIdByPrincipal(principal) I get a NPE. I am not sure why. Ideally, what I want is for the method call to return 1, I don't care about testing those function internal in this unit test.
Actual Code
Boolean requesterOwnsGoal(Principal principal, Goal goal) {
Optional<Goal> optionalGoal = Optional.ofNullable(goal);
if (optionalGoal.isPresent()) {
return secService.getUserIdByPrincipal(principal) == optionalGoal.get().getUsersUserId();
}
throw new StandardUserException("Requesting user does not have access to goal");
}
Stack:
java.lang.NullPointerException
at com.habicus.core.service.Goal.GoalService.requesterOwnsGoal(GoalService.java:170)
at com.habicus.core.service.Goal.GoalServiceTest.testRequesterOwnsGoalIsTrue(GoalServiceTest.java:82)
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.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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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)
It should be doReturn(1).when(securityService).getUserIdByPrincipal(any(principal)); to make it work.
Or
doReturn(1).when(securityService).getUserIdByPrincipal(any(Principal.class));
The code shown so far indicates that you are in fact creating a mock object. But you are not injecting that mock into your class under test!
Just creating mocks isn't sufficient. You have to ensure that they get used by the code you are testing!
Most likely that is your problem here, but as we still don't have a [mcve] we can't be sure.
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.
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.