easymock two setAttributes for one session - junit

I have created a session in the test class. and return it when getsession is called.
expect(request.getSession()).andReturn(session);
I have set two different attributes for the session as they are set in the method which I want to test.
session.setAttribute("name","xyz");
session.setAttribute("class", "A")'
When I call the method, in the when it tries to setAttribue, it causes a nullpointerexception.
Any help?

It can be problem if you set the values after making expect method.
User user=new User();
expect(mock.getUser()).andReturn(user);
user.setName("John"); //It should be above the expect line
Or you forget to call EasyMock replay() method on your mock after expect method.
// Setup the method of mock object
expect(mock.getNum()).andReturn(2)
// Setup is finished need to activate the mock
replay(mock);

Related

Mockito: use InOrder with spy object

I want to check the invocation order of some methods using mockito. One of the methods I want to check is on a mock, the other one is in the real class that I am testing, so I am using a spy object for checking that:
However, mockito is only aware about calls on the mock methods, but not on the spy object:
MigrationServiceImpl migrationServiceSpy = spy(migrationServiceImpl);
// I have tested without no more configuraitons on the spy, and also with the following
// by separate (one by one)
// I tried this:
doNothing().when(migrationServiceSpy).updateCheckpointDate(eq(migration), any(Instant.class)); // In this case the call is not tracked by InOrder
// And this:
when(migrationServiceSpy.updateCheckpointDate(eq(migration), any(Instant.class))).thenReturn(true); // In this case the call is not tracked by InOrder
// And this:
when(migrationServiceSpy.updateCheckpointDate(eq(migration), any(Instant.class))).thenCallRealMethod(); // This line is throwing a null pointer exception but I don't understand why, since if I do not spy the real object it works without failing.
//Here I call the real method
migrationServiceImpl.updateStatus(DEFAULT_MIGRATION_ID, inProgressStatus);
InOrder inOrder = inOrder(migrationServiceSpy, mongoMigrationRunner);
inOrder.verify(migrationServiceSpy).updateCheckpointDate(any(Migration.class), any(Instant.class));
inOrder.verify(mongoMigrationRunner).runMigrationForInterval(any(Migration.class), anyString(), any(Instant[].class));
What can I do? What's hapenning?
The solution was to make the call on the spy object instead the real object:
migrationServiceSpy.updateStatus(DEFAULT_MIGRATION_ID, inProgressStatus);
instead of:
migrationServiceImpl.updateStatus(DEFAULT_MIGRATION_ID, inProgressStatus);

method under test parameters doesn't change

Well, I'm doing simple test to understand junit and to be honest I don't understand why
#Test
void findById() {
Long id= 2L;
Visit returnedVisit = service.findById(id);
assertEquals(Long.valueOf(4L),id);
}
id is equal 2 after changing value in tested method
public Visit findById(Long aLong) {
aLong= 4L;
return new Visit();
}
This is because the local primitive variable id in one method (your test case) is set to 2. It is then passed by value to the other method. Passing by value means to put an exact bit-wise copy on the call stack. That called method sets its local copy of the variable, but that does not modify the caller's variable.
If you passed a list, you would see modifications, because the list reference is passed by value, and you can make changes to the list like adding new elements, and the caller's list is modified. You can also modify the reference to the list, but the caller won't see it, i.e., if you reassign the list to some new list in the called method, the caller will still have the old list.
This is just how Java passes parameters; it has nothing to do with JUnit.
See also this question and its answers.

powermockito static and non static method chain

I want non-static method of an object returned by a static factory method to return a specific result.
After I have done this setup my test code will be calling the ConnectionFactory.getConn("ABC") indirectly through another piece of code which is being tested.
PowerMockito.when(ConnectionFactory.getConn("ABC").getCurrentStatus()).thenReturn(ConnectionStatus.CONNECTED);
I get a NPE for the above statement.
I already have #PrepareForTest({FXAllConnectionFactory.class, ConnectionStatus.class}) at the beginning of my junit test class.
What would be the correct way of doing it?
Thanks in advance :)
I guess there is no point in creating a fluent/chained call for your test setup.
You see:
PowerMockito.when(ConnectionFactory.getConn("ABC").getCurrentStatus()).thenReturn(ConnectionStatus.CONNECTED);
is probably meant to configure two calls:
ConnectionFactory.getConn("ABC") and then
getCurrentStatus() on the result of that first call
And what makes you think that PowerMockito magically knows what should be returned by that first call to getConn()?
In other words:
First provide a mocked Connection object X; and configure your mocks so that getConn() returns that object
In addition to that, you have to configure X to return the desired value upon a call to getCurrentStatus() ... on X!
So, the answer is actually: what you want to do isn't possible. The idea is; you specify behavior such as:
when A.foo() is called; then return some X
There is no magic power within PowerMockito to turn
when A.foo().bar() is called thren return Y
into
when A.foo() is called, return X; when X.bar() is called return Y
You have to specify that step by step.

Use session inside src/groovy

I want to set a value in session inside a function A() in src/groovy class and use that value inside function B() in the same src/groovy class. Is that possible? I cannot pass the value between functions since they are overridden. I referenced this link but did not quite understand the implementation. Thanks in advance.
Edit: Here function A is visit function of crawler4j and function B is handlePageStatusCode()
The link you've referenced is the way to go - the static method RequestContextHolder.getRequestAttributes() will give you the instance of GrailsWebRequest that belongs to the currently-executing request, or null if you call it on a thread that is not running a controller action. Once you have the GrailsWebRequest you can access the session, request, response, params and flash (via getFlashScope()) from there.
I made a little utility Java class to handle accessing the session in places like src/groovy, src/java or grails-app/services. You could try using it:
public class SessionUtil {
/**
* Returns the current session. This can be used in classes where the session variable is not set by Grails, such as Services.
* #return the session
*/
public static GrailsHttpSession getSession() {
return WebUtils.retrieveGrailsWebRequest().getSession();
}
}
To use it, wherever you need the session you would write:
def session = SessionUtil.getSession()
It's hard to understand quite what you are trying to achieve here. A session only makes sense in terms of a connected user, during an HTTP request. If you are using the src/groovy class from e.g. a controller, you could pass the session to your method as an argument to the method. Otherwise how would you be using it?

mockito when thenReturn does not return stubbed array list

List<Populate> fullAttrPopulateList = getFullAtrributesPopulateList(); //Prepare return list
when(mockEmployeeDao.getPopulateList(null)).thenReturn(fullAttrPopulateList);
MyDTO myDto = testablePopService.getMyPopData(); //Will call mockEmployeeDao.getPopulateList(null)
//verify(mockEmployeeDao,times(1)).getPopulateList(null);
assertEquals(fullAttrPopulateList.size(), myDto.getPopData().size()); //This fails because myDto.getPopData().size() returns 0
As you can see testablePopService.getMyPopData() calls mockEmployeeDao.getPopulateList(null) but when I debug it a zero sized list returns instead of the stubbed array list which is prepared by getFullAtrributesPopulateList();
If I uncomment the verify statement, it passes the test meaning getPopulateList(null) behavior does get called.
Can anyone give me some advice why my stubbed array list cannot be returned even it is verified the expected behavior happened? How come an empty array list returns rather than a null if I did something wrong?
First, check that the method is non-final and visible throughout its hierarchy. Mockito can have trouble mocking methods that are hidden (e.g. overriding a package-private abstract class's implementation); also, Mockito is entirely unable to mock final methods, or even to detect that the method is final and warn you about it.
You may also want to check that your call is using the overload you expect. Mockito's default list return value is an empty list, so you may simply stubbing one method and seeing the default value for another. You can see which method interactions Mockito has added by adding a call to verifyZeroInteractions temporarily, and Mockito will throw an exception with a list of calls that mock has received. You could also add verifyNoMoreInteractions, and even leave it in there, at the expense of test brittleness (i.e. the test breaks when the actual code continues to work).