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.
Related
I did see this post: Method invocation vs method execution but to me it does not quite make sense. I thought in order to execute the method, we must call the method, but both are two separate things in my opinion. The execution of the method is separate thing than the method call itself. I am unable to see how they are the same thing.
I think you're overthinking about it.
Calling a method or a method getting executed are the exact same thing.
Or you could say, a method gets executed when it gets called.
Eg:
calling the method here
int x = returnThatInteger();
some where else in the code
public int returnThatInteger(){ // method executing here
return 1;
}
So you're right,
in order to execute the method, we must call the method
How to mock a void protected Method in a filter using mockito and make it return some "response"
since it's a void method ,i cannot use doReturn(some value) ,is there a way to set a response and make
it return that.
The short answer is that you can't, the long answer is that even if you could, you shouldn't.
The purpose of your test should be to verify the behaviour of your class/method. What does your filter do? What are the possible paths through the code? It must either return a value, have a side-effect or communicate with another object. These are the things that you should be testing for.
For example, seeing as this is a filter chain I assume that it's going to apply some logic and either call the next filter or not. You should mock the next filter in the chain and assert that it's called correctly or not depending on your logic.
I don't think we can return any response from methods that returns void but in case if we want to mock a method that returns void we could use:
Mockito.doNothing().when(apiService).methodNamethatReturnsVoid(Mockito.anyString();
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).
When I test a method the inner of the method invokes itself and another method that is in the same class. I use a partial mock to specify the other method's return value but how do I specify the first method's return value?
If you are mocking the method, then it is no longer recursive - because the mock will only return the final return value that would be returned after recursion.
If you want to test the recursive function, then don't mock the recursive method.
Your explanation is a little unclear, but perhaps just mocking the other method that is called is sufficient for your test. You can make sure that other method gets called with the correct parameters.
lets try returnsMany in mockk:
coEvery{ mockEntity.recursiveMethod()}.returnsMany(value1, value2,...)
The first call recursiveMethod() will return value1, then the second call return value2,...
Handle your recursive flow in the right way
I'm trying to setup a test in JUnit w/ EasyMock and I'm running into a small issue that I can't seem to wrap my head around. I was hoping someone here could help.
Here is a simplified version of the method I'm trying to test:
public void myMethod() {
//(...)
Obj myObj = this.service.getObj(param);
if (myObj.getExtId() != null) {
OtherObj otherObj = new OtherObj();
otherObj.setId(myObj.getExtId());
this.dao.insert(otherObj);
}
//(...)
}
Ok so using EasyMock I've mocked the service.getObj(myObj) call and that works fine.
My problem comes when JUnit hits the dao.insert(otherObj) call. EasyMock throws a *Unexpected Method Call* on it.
I wouldn't mind mocking that dao in my test and using expectLastCall().once(); on it, but that assumes that I have a handle on the "otherObj" that's passed as a parameter at insert time...
Which of course I don't since it's conditionally created within the context of the method being tested.
Anyone has ever had to deal with that and somehow solved it?
Thanks.
You could also use EasyMock.isA(OtherObj.class) for a little more type safety.
If you can't get a reference to the object itself in your test code, you could use EasyMock.anyObject() as the expected argument to yourinsert method. As the name suggests, it will expect the method to be called with.. well, any object :)
It's maybe a little less rigorous than matching the exact argument, but if you're happy with it, give it a spin. Remember to include the cast to OtherObjwhen declaring the expected method call.
The anyObject() matcher works great if you just want to get past this call, but if you actually want to validate the constructed object is what you thought it was going to be, you can use a Capture. It would look something like:
Capture<OtherObj> capturedOtherObj = new Capture<OtherObj>();
mockDao.insert(capture(capturedOtherObj));
replay(mockDao);
objUnderTest.myMethod();
assertThat("captured what you expected", capturedOtherObj.getValue().getId(),
equalTo(expectedId));
Also, PowerMock has the ability to expect an object to be constructed, so you could look into that if you wanted.
Note also that if you use EasyMock.createStrictMock();, the order of the method calls is also important and if you break this rule, it would throw an unexpected method call.