How to call a method from a mocked interface using EasyMock - java

I am writing a Junit unit test for a class and I am getting a java.lang.NullPointerException on the following line :
expect(lineConfigurationHandlerMock.getDeviceControlHandler().getDeviceParameters(item1)).andReturn(myDeviceParameters);
I think (i am not sure though) that it has something to do with the method (getDeviceControlHandler) that I am calling from within the mocked interface . Because I have added this line of code before the submentioned line:
Assert.assertNotNull(comLineConfigurationHandlerMock.getDeviceControlHandler());
And I am having the following error:
java.lang.AssertionError
I am stuck here and really need some help.
Thanks in Advance.
The thrown Exception:
java.lang.NullPointerException
at de.myproject.project.classTest.testGetParameters(classTest.java:123)
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.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)
Here is the written test:
public class classTest {
// class under test
private classUnderTest classUnderTest;
private LineConfigurationHandler LineConfigurationHandlerMock;
private IMocksControl mocksControl;
List<DeviceParameter> myDeviceParameters;
DeviceParameter deviceParameter1;
DeviceParameter deviceParameter2;
#Before
public void setUp() throws Exception
{
mocksControl = EasyMock.createControl();
LineConfigurationHandlerMock = mocksControl.createMock(LineConfigurationHandler.class);
classUnderTest = new classUnderTest();
classUnderTest.setLineConfigurationHandler(LineConfigurationHandlerMock);
String item1 = "item1";
myDeviceParameters = new ArrayList<DeviceParameter>();
myDeviceParameters.add(deviceParameter1);
myDeviceParameters.add(deviceParameter2);
//Other stuff
}
#Test
public void testGetParameters()
{
expect(LineConfigurationHandlerMock.getDeviceControlHandler().getDeviceParameters(item1)).andReturn(myDeviceParameters);
mocksControl.replay();
//Some code .....
}
}
Here is the class under test :
public Class ClassUnderTest
{
#Inject
private LineConfigurationHandler lineConfigurationHandler;
public List<DeviceParameter> getDeviceParameters(String deviceId)
{
// Method implementation
}
#Required
public void setLineConfigurationHandler(LineConfigurationHandler lineConfigurationHandler)
{
this.lineConfigurationHandler = lineConfigurationHandler;
}
}
The interface in which the method is declared
public interface LineConfigurationHandler {
DeviceControlHandler getDeviceControlHandler();
//other Method declaration ...
}
DeviceControlHandler.class
public interface DeviceControlHandler extends Serializable{
List<DeviceParameter> getDeviceParameters(String deviceId);
//Other methods declaration ...
}

It is not simple, but very deterministic:
expect(lineConfigurationHandlerMock.getDeviceControlHandler().getDeviceParameters(item1)).andReturn(myDeviceParameters);
That line contains two items that can throw NPE:
A) lineConfigurationHandlerMock --> that object can be NULL
B) .getDeviceControlHandler() --> that method can return NULL
That's it. You can do simple printouts, like
System.out.println("mock: " + lineConfigurationHandlerMock)
System.out.println("handler: " + lineConfigurationHandlerMock.getDeviceControlHandler())
to figure which one is null. In your case, I think you are missing the setup for your lineConfigurationHandlerMock object: you have to tell it what to return when getDeviceControlHandler() is called.
In order to do that, you first have to create another mock object that should be returned when getDeviceControlHandler() is called. And that other mock, you have to configure for a call to getDeviceParameters()!
In other words: you can't specify like "mock.getA().doSomething()" - instead, you need another "mockedA" which you tell "doSomething()"; and then you tell "mock" that getA() should return "mockedA".
Update: I am not familiar with these annotations; I am used to use "EasyMock in a bare metal mode"; like
SomeObject innerMock = EasyMock.createMock(SomeObject);
expect(innerMock.doSomething()).andReturn("who cares");
SomeOther outerMock = EasyMock.createMock(SomeOther);
expect(outerMock.getDeviceControlHandler("sounds familiar")).andReturn(innerMock);

Related

java.lang.NullPointerException is occuring due to property is not loading in Mockito when mocking a method

I am new to Mockito and i am facing a issue due to a property is not loading in from appication.properties file.
Problem statement: I am trying to mock a method which uses a property from the application.properties file. When the control arrives at the line to load property value it shows null and because of this mockito throws java.lang.NullPointerException.
What i am looking for is how to load the property from application.properties file when mocking a method.
Here i am trying to load global variable partsListGlobal .Please help me how to achieve this.?
Here is my below code snippet.
#Service
public class ClimoDiagnosticReportServImpl implements ClimoDiagnosticReportService {
#Value("${PARTS_LIST}")
private String partsListGlobal;
#Override
public boolean getSomeResult() {
String[] partsListLocal = getPartsList();
List<String> partsList = Arrays.asList(partsListGlobal);
if (partsList.contains("PART_X1"))
return true;
else
return false;
}
public String[] getPartsList() {
return partsListGlobal.split(",");// Here is the error occuring due to partsListGlobal is not loading the value from application.properties file.
}
}
#RunWith(MockitoJUnitRunner.class)
public class ClimoDiagnosticReportServImplTest {
#InjectMocks
private ClimoDiagnosticReportServImpl serviceReference1;
#Mock
private ClimoDiagnosticReportServImpl serviceReference12;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void getSomeResultTest() {
boolean result1 = false;
String[] strArray = new String[2];
strArray[0] = "P1";
strArray[1] = "P2";
Mockito.when(serviceReference12.getPartsList()).thenReturn(strArray);
boolean result2 = serviceReference1.getSomeResult();
Assert.assertEquals(result1,result2);
}
}
Error:
java.lang.NullPointerException at
com.test.serviceimpl.ClimoDiagnosticReportServImpl.getPartsList(ClimoDiagnosticReportServImpl.java:68)
at
com.test.serviceimpl.ClimoDiagnosticReportServImpl.getSomeResult(ClimoDiagnosticReportServImpl.java:57)
at
com.test.serviceimpl.ClimoDiagnosticReportServImplTest.getSomeResultTest(ClimoDiagnosticReportServImplTest.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: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.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)
Thanks everyone in advance.
You don't have any dependency to mock in the service. Mockito is thus completely unnecessary. What you need to do is to set the private String field, that is populated by Spring in your application using reflection.
Just follow the best practice os using cnstructor injection instead of field injection, and that will make your code testable (that's one of the reasons why it's a best practice):
#Service
public class ClimoDiagnosticReportServImpl implements ClimoDiagnosticReportService {
private String partsListGlobal;
public ClimoDiagnosticReportServImpl(#Value("${PARTS_LIST}") String partsListGlobal) {
this.partsListGlobal = partsListGlobal;
}
// ...
}
Your test now can be reduced to
public class ClimoDiagnosticReportServImplTest {
#Test
public void shouldReturnTrueIfPropertyContainsPartX1() {
ClimoDiagnosticReportServImpl service = new ClimoDiagnosticReportServImpl("a,b,c,PART_X1,d");
assertTrue(service.getSomeResult());
}
#Test
public void shouldReturnFalseIfPropertyDoesNotContainPartX1() {
ClimoDiagnosticReportServImpl service = new ClimoDiagnosticReportServImpl("a,b,c,d");
assertFalse(service.getSomeResult());
}
}

Mocking DeleteResult of MongoDB using Mockito in Java

The unit test below is not able to mock DeleteResult for the Java code being tested. Getting a NullPointerException. I'm running the test on JUnit. Is it something to do with the Filters in the delete statement?
#InjectMocks
DBConnection mongoConnect;
#Mock
MongoClient mockClient;
#Mock
MongoCollection<Document> mockCollection;
#Mock
MongoDatabase mockDB;
#Mock
LinkedList<String> mockArrList;
#Mock
MongoIterable<String> mongoIter;
#Mock
DeleteResult mockDeleteResult;
#SuppressWarnings("unchecked")
#Test
public void deleteDocTest1() {
Mockito.when(mockClient.getDatabase(Mockito.anyString())).thenReturn(mockDB);
MongoIterable<String> mongoIter = Mockito.mock(MongoIterable.class);
Mockito.when(mockDB.listCollectionNames()).thenReturn(mongoIter);
Mockito.when(mongoIter.into(new LinkedList<String>())).thenReturn(mockArrList);
Mockito.when(mockArrList.contains(Mockito.anyString())).thenReturn(true);
Mockito.when(mockDB.getCollection(Mockito.anyString())).thenReturn(mockCollection);
Mockito.when(mockCollection.deleteOne(Filters.and(Filters.eq("aid", "TS123"),
Filters.eq("year", "2018"),
Filters.eq("position", "testCases"))))
.thenReturn(mockDeleteResult);
Mockito.when(mockDeleteResult.getDeletedCount()).thenReturn(1L);
String msg = mongoConnect.deleteDocument("TS123", "testCases", "2018");
assertEquals("Delete Successful", msg);
}
The code being tested just has to delete a record if the keys match, and return a warning if there is no such record. The method below, which is being tested, is part of DBCollection class:
public String deleteDocument(String aId, String collection, String year) {
MongoDatabase database = mongoClient.getDatabase(databaseName);
//checking if collection is present in the DB
boolean collectionExists = database.listCollectionNames().into(new LinkedList<String>())
.contains(collection);
if(collectionExists) {
MongoCollection<Document> collectionDocs = database.getCollection(collection);
System.out.println(assoId+" "+collection+" "+year);
DeleteResult deleteResult = collectionDocs.deleteOne(Filters.and(Filters.eq("aid", aId), Filters.eq("year",year), Filters.eq("position",collection)));
if(deleteResult.getDeletedCount() == 0) //the ERROR is at this line
return "Delete: record does not exist";
}else {
return "Delete: record does not exist";
}
mongoClient.close();
return "Successful Delete";
}
The stack trace for the error:
java.lang.NullPointerException
at com.repo.repository.DBConnection.deleteDocument(DBConnection.java:103)
at com.repo.form_upload.test.DBTest.deleteDocTest1(DBTest.java:138)
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.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)
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)
Any ideas on what's the problem?
The issue here is with this expectation:
Mockito.when(mockCollection.deleteOne(Filters.and(Filters.eq("aid", "TS123"),
Filters.eq("year", "2018"),
Filters.eq("position", "testCases"))))
.thenReturn(mockDeleteResult);
Bson does not implement equals so when Mockito attempts to determine whether it should return something from the collectionsDocs.deleteOne call in your deleteDocument it cannot match the filter argument so it determines that collectionsDocs.deleteOne returns nothing. To verify this, just run the following code:
Bson one = Filters.and(Filters.eq("aid", "TS123"),
Filters.eq("year", "2018"),
Filters.eq("position", "testCases"));
Bson two = Filters.and(Filters.eq("aid", "TS123"),
Filters.eq("year", "2018"),
Filters.eq("position", "testCases"));
// one and two are not equal because Bson does not implement equals so
// we'll just fall back to the standard instance check in Object
assertNotEquals(one, two);
Your test will pass - albeit with less specificity about the filters - if you express the deleteOne expectation like this:
Mockito.when(mockCollection.deleteOne(any(Bson.class))).thenReturn(mockDeleteResult);
Alternatively you could use a custom matcher to apply your own equals check on the Bson. For example, you would change the mockCollection.deleteOne expectation to the following:
Mockito.when(mockCollection.deleteOne(argThat(new BsonMatcher(Filters.and(Filters.eq("aid", "TS123"),
Filters.eq("year", "2018"),
Filters.eq("position", "testCases"))))))
.thenReturn(mockDeleteResult);
And declare the BsonMatcher as follows:
public class BsonMatcher implements ArgumentMatcher<Bson> {
private BsonDocument left;
public BsonMatcher(Bson left) {
this.left = left.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
}
#Override
public boolean matches(Bson right) {
// compare as BsonDocument, since this does provide an equals()
return left.equals(right.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry()));
}
}
Note you'll also need to change your assertEquals("Delete Successful", msg); to assertEquals("Successful Delete", msg); because deleteDocument returns "Successful Delete" :)

ModelMapper JUnit Mockito throws NullPointerException

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.

Spring junit test Error "could not find current request via RequestContextHolder"

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.

Mocking a post request with Mockito throws NullPointerException on "when(event.request().getParam("type")).thenReturn("application/octet-stream");"

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/oct‌​et-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");

Categories

Resources