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.
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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
java.lang.NullPointerException at
com.Accounts.Account.deposit(Account.java:14) at
feature.PrintStatementFeature.print_statement_containing_all_transactions(PrintStatementFeature.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.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:68)
at
org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:74)
at
org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at
org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:161)
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 Code is this
package feature;
#RunWith(MockitoJUnitRunner.class)
public class PrintStatementFeature {
#Mock Console console;
private Account account;
#Before
public void initialise() {
TransactionRepository transactionRepository = new TransactionRepository();
account = new Account(transactionRepository); //now create its local variable.
}
#Test public void
print_statement_containing_all_transactions ()
{
account.deposit(1000);
account.withdraw(100);
account.deposit(500);
account.printStatement();
InOrder inOrder = inOrder(console);
inOrder.verify(console).printLine("DATE.........|...AMOUNT...|...BALANCE... ");
inOrder.verify(console).printLine("17/04/2015...|....500.....|.....1400.... ");
inOrder.verify(console).printLine("15/04/2015...|...-100.....|.....1400.... ");
inOrder.verify(console).printLine("10/04/2015...|....1000....|.....1500.... ");
}
}
NullPointerExceptions are allways an Error, because there is missing a Instance.
Try the workaround from the commands if(Account.deposit == null){ ... } or post some more code.
I´m writing jUnit-Tests a long time and i guess you´ve just mocked/created a dummy of a wrapper class but you forgot to create the needed members for this test.
Try to create Helper-Classes for your tests so thei can create every needed Dummy-Class for your test empty and with random fillings.
I'm trying to mock a file upload (using Vertx) with Mockito but it throws a NullPointerError on getParam("type") used in when(event.request().getParam("type")).thenReturn("application/octet-stream");
My unit test is as follows:
private UploadResultatenHandler uploadResultatenHandler;
#Mock
RoutingContext event;
File folder;
Set<io.vertx.ext.web.FileUpload> upload;
HttpServerRequest httpServerRequest;
HttpServerResponse httpServerResponse;
#Before
public void setUp() {
uploadResultatenHandler = new UploadResultatenHandler();
MockitoAnnotations.initMocks(this);
when(event.request().getParam("type")).thenReturn("application/octet-stream");
when(event.fileUploads()).thenReturn(upload);
when(httpServerResponse.setStatusCode(200)).thenReturn(httpServerResponse);
when(event.response()).thenReturn(httpServerResponse);
}
#Test
public void testCleanHandler() {
uploadResultatenHandler.handle(event);
verify(event).response();
}
"uploadResultatenHandler.handle(event);" :
#Override
public void handle(RoutingContext event) {
String newFileName = event.request().getParam("type");
Set<FileUpload> uploads = event.fileUploads();
System.out.println(uploads);
for (FileUpload fileUpload : uploads) {
String oldFileName = fileUpload.uploadedFileName();
char[] inhoud = FileReader.readFileUTF8ToString(oldFileName).toCharArray();
String fileExtention = setFileExtension(fileUpload.contentType());
FileCreater.createFile(newFileName, fileExtention, "file-uploads/", inhoud);
FileDeleter.deleteFile(oldFileName);
}
event.response().setStatusCode(200).end("Check");
}
private String setFileExtension(String type) {
switch (type) {
case "text/xml":
return ".xml";
case "application/octet-stream":
return ".json";
default:
return ".txt";
}
}
I think it might have something to do with the mocked RoutingContext not having this parameter, but I don't know how to fix / bypass this error?
I changed the line to when(event.request()).thenReturn(request); when(request.getParam("type")).thenReturn("application/octet-stream"); and the mocks to: Mock(answer = Answers.RETURNS_DEEP_STUBS) RoutingContext event; #Mock File folder; Set upload; HttpServerRequest request; HttpServerResponse response; but I'm still getting a NullPointer
Stack trace:
java.lang.NullPointerException
at nl.icaprojecten.TestIntegratieQuintor.ServiceLayer.rest.UploadResultatenHandlerTest.setUp(UploadResultatenHandlerTest.java:42)
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.RunBefores.evaluate(RunBefores.java:24)
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.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)
Since you haven't recorded any behavior for event.request(), it will return null. Calling getParam on it will, of course, fail with a NullPointerException. There are a few ways around it, but the most elegant, IMHO, would be to use deep stubbing:
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
RoutingContext event;
mocking does not work recursively.
you must split this line
when(event.request().getParam("type")).thenReturn("application/octet-stream");
to this
Request request = mock(Request.class);
when(event.request()).thenReturn(request);
when(request.getParam("type")).thenReturn("application/octet-stream");
I have the below test class, which has been stripped to the bare minimum needed to reproduce the issue:
#RunWith(Parameterized.class)
#ContextConfiguration(locations = { "classpath:restful-service-test-context.xml" })
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class ResftulServiceTest {
#Autowired
#Qualifier("failedAspectTestMessage")
private String failedAspectTestMessage;
#Autowired
private ProviderService ProviderService;
private String methodName;
private Set valuesToReturnByMock;
private TestContextManager testContextManager;
public ResftulServiceTest(String methodName, String[] valuesToReturnByMockArray) {
this.methodName = methodName;
this.valuesToReturnByMock = new HashSet<>(Arrays.asList(valuesToReturnByMockArray));
}
#Parameterized.Parameters
public static Collection values() {
return Arrays.asList(new Object[][] { { "getCountries", new String[] { "GB", "US" } }, });
}
#Before
public void setUpSpringContext() throws Exception {
testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
}
#Test
public void testGetValues_Fail_MyException() throws Exception {
Method methodInProviderService = ProviderService.class.getDeclaredMethod(methodName);
Mockito.when(methodInProviderService.invoke(ProviderService))
.thenThrow(new MyException(failedAspectTestMessage, StatusCodeType.ERROR));
}
#Test
public void testGetValues_Fail_Exception() throws Exception {
Method methodInProviderService = ProviderService.class.getDeclaredMethod(methodName);
Mockito.when(methodInProviderService.invoke(ProviderService))
.thenThrow(new AspectException(failedAspectTestMessage));
}
}
If I run each of the tests separately, they work fine. However, if I run all of them, testGetValues_Fail_Exception fails on the Mockito line with error:
java.lang.reflect.InvocationTargetException
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:497)
at com<obfuscated>.ResftulServiceTest.testGetValues_Fail_Exception(ResftulServiceTest.java:111)
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:497)
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.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.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: com.<obfuscated>.MyException: FAILED_ASPECT_TEST_MESSAGE
... 40 more
If I replace the .thenThrow in testGetValues_Fail_MyException with .thenReturn, it all works fine, so at some point the isolation is being broken. How can I fix this problem?
Try using Mockito.reset() passing your mock. Usually this is done to prevent interaction between test. It resets the previously configured behavior of the mock. However, in your case I cannot give more details as you are using an unusual combination of Parameterized with Spring context and DirtiesContext.
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.