EasyMock expected void - jpa-2.0

Just trying the EasyMock for the first time.
I seem to get it going but I am immediately halted with the fact that the mocked class runs a method "returning" void (EntityManager.remove(abc)).
I am able to mock the EntityManger partly to begin testing, i.e.
EasyMock.expect(this.mockManager.find(Some.class, id)).andReturn(mock);
, but how do I do the same for the 'remove' case?
I can't do (for example):
EasyMock.expect(this.mockManager.remove(rek)).andReturn(Boolean(true));
And if I do nothing, I get:
java.lang.AssertionError:
Unexpected method call EntityManager.remove(EasyMock for class my.package.Some)...
I need to test the logic before getting to remove part, but I don't care if it actually succeeds (would be a different thing).

You don't need to call EasyMock.expect(). Just use
this.mockManager.remove(rek);
while in the recording phase (before calling replay()).
If you want the mocked method, for example, to throw an exception or to be called twice, use expectLastCal():
this.mockManager.remove(rek);
expectLastCall().andThrow(new RuntimeException());
//or expectLastCall().times(2);

Related

googlemock EXPECT_CALL with small behaviour variations

With the help of googlemock and googletest, I set up a test that checks that different mocked errors are correctly handled by the method under test. Basically my code looks like this:
// setup mock object, and object under test
// setup initial EXPECT_CALL expectations
// this expected method call in the middle mocks a failure
EXPECT_CALL(*mock, method(arg_in)).
Times(1).
WillOnce(Throw(exception_of_type_A));
// setup cleanup EXPECT_CALL expectations
// Now invoke method in object under test.
// Expect exception has been translated to different type.
EXPECT_THROW(x.method_under_test(), exception_type_B);
// destructor of mock object will check the mock method invocations
Now my mocked method that fails here can not only fail by throwing an exception of type A, but also by throwing an exception of type B, or by returning an unexpected return value.
I can implement this easily enough by copying and pasting the complete TEST() and just changing what the misbehaving mocked method1 will do. But this will make the code messy. Even if I document that these 3 tests are exactly the same except for how the mocked method1 fails in the WillOnce() action specification, a human reader would still have to compare carefully if this is still true.
What would be the correct way in googletest/googlemock to share the common code between the three TESTS and just have them differ in the WillOnce() action?
To my mind comes: Macros, loops over a container with WillOnce() actions, googletest fixtures, static helper methods for setup and cleanup.
I am still new to googletest and not sure how to address this.
For now, I implement the test logic in a templated static function that accepts an action as a parameter:
template <typename A>
static void paramererizeable_test(A failingAction) {
// set everything up
EXPECT_CALL(*mock, method(arg_in)).
Times(1).
WillOnce(failingAction);
// set up more expectations
// trigger the calls
}
TEST(Section, Method) {
paramererizeable_test(Throw(exception_of_type_A));
paramererizeable_test(Throw(exception_of_type_B));
paramererizeable_test(Return(unexpected_return_value));
}
Not sure if this is how it should be done, or if there is a better way, but it works and is readable.

How to avoid Collection.sort() method from executing in a test case?

Hi I am writing unit test cases for a program. In that program I am testing a certain method in which their is this method : Collections.sort(Arraylist object).
Its something like this.
public void abc(){
try{
Arraylist<object_class> object=some_method.get(list);
Collections.sort(object);
System.out.print("The whole functon is executing successfully") }
catch(exception e) {
system.out.print("error message") } }
the some_method.get(list)` method I am calling is sending a empty list so when Collections.sort() is called it goes to catch block and the rest code is not executed.
What can i do so that this Collections.sort() method is not called while test case is running.
PS- above code is only to explain the question and I cant make changes to main class
In test class I tried to use this method
Mockito.doNothing().when(collections.sort(Mockito.anyList()));//this is not working
So I tried this Mockito.doNothing().when(collections.class).sort(Mockito.anyList()); //this is also not working
I can return a mock list to object but I want to know if I can prevent Collections.sort() from executing.
Please help
It' simple if you want to execute Collections.sort() without any exception follow below steps:
1) Create a list object with dummy values in your test class and send it to main class
list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
2) Second step is make sure that your
some_method.get(list);
returns a ArrayList of objects,
3) As Collections class has static method sort, JVM will execute rest of the code as usual. And will not through any exception.
PS- If Mockito.doNothing() is not working try with PowerMockito.doNothing(), it might work and make sure that you have
1) #PrepareforTest(Collections.class)
2) PowerMockito.mockStatic(Collections.class);
3) PowerMockito.doNothing().when(Collections.sort(obj));
Hope it's useful.
This is wrong on many levels:
You are using a raw type there (by using ArrayList without a generic type parameter) - never do that!
If your test setup makes that other method return null, then don't manipulate "later" code - instead either avoid that null or make sure your production code can deal with it!
In other words: there are only two reasonable choices:
A) if in reality, that method never returns null. Then you should make sure, that this is also true for your test setup.
B) if in reality, that method returns null, too ... then your production code needs to deal with that, for example by doing a null check before calling sort!
Finally: especially for lists, that problem really doesn't exist at all: the answer is - you never ever return null! Instead, you return an empty list if there is no data. Empty lists can be sorted without a problem! Long story short: avoid returning null in the first place.
I can return a mock list to object but I want to know if I can prevent Collections.sort() from executing.
I don't see a way to prevent that
Collections.sort() is executed as long as the method that calls it is executed and as long as you can't change the tested code. The reason is that sort is a static method. You can pass or inject an instance that is a mock to achieve your goal.
Returning a mock list that can be sorted is the way to go in my opinion. If you manipulate the behavior of the tested class during test you will have a higher risk not to find errors. Additionally, you have a tight coupling between test and tested class in this case.

Mockito Verify method not giving consistent results

I'm learning GwtMockito but having trouble getting consistent verify() method results in one of my tests.
I'm trying to test the correct GwtEvents are being fired by my application. So I've mocked the Event Bus like this in my #Before method:
eventBus = mock(HandlerManager.class);
This test passes as expected:
// Passes as expected
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));
I wanted to force the test to fail just to know it was running correctly. So I changed it to this and it still passes:
// Expected this to fail, but it passes
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));
verifyZeroInteractions(eventBus).fireEvent(any(ErrorOccurredEvent.class));
This seems contradictory to me. So I removed the first test:
// Fails as expected
verifyZeroInteractions(eventBus).fireEvent(any(ErrorOccurredEvent.class));
Finally I added an unrelated event that should cause it to fail
// Expected to fail, but passes
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));
verify(eventBus).fireEvent(any(ModelCreatedEvent.class)); // This event is not used at all by the class that I'm testing. It's not possible for it to be fired.
I'm not finding any documentation that explains what's going on. Both ErrorOccurredEvent and ModelCreatedEvent extend GwtEvent, and have been verified in manual testing. Am I testing my EventBus incorrectly? If so, what is a better way to go about it?
Update
I've done some additional experimenting. It appears to be an issue I'm having with the Mockito matcher. When I get the test to fail the exception reports the method signature as eventBus.fireEvent(<any>) so it doesn't appear to be taking into account the different classes I'm passing into the any method. Not sure what to do about this yet, but including it here for anyone else researching this problem.
The method you're looking for is isA, instead of any.
This doesn't explain my first attempt to force the test to fail, but it does explain the other confusion. From the Mockito documentation:
public static T any(java.lang.Class clazz)
Matches any object, including nulls
This method doesn't do type checks with the given parameter, it is
only there to avoid casting in your code. This might however change
(type checks could be added) in a future major release.
So by design it doesn't do the type checks I was hoping for. I'll have to work out another way to design these tests. But this explains why they weren't behaving as I expected.

How to only throw exception when the mocked method is called for the first time?

I have a method of a mocked object that can be called multiple times (think recursion). The method is defined like this:
public void doCommit() { }
In order to tell it to fail I use this convention:
doThrow(new RuntimeException()).when(mMockedObject).doCommit();
This though, makes the method throw this exception EVERY time it is called. How can I make it so that it only, for example, throws it the first and third time it is called? Which means that, for example, the second and forth time it just returns without throwing an exception. Please note that I am not the author of doCommit(), nor do I have source code that I can change.
I figured it out (with some hints from Igor). This is how you stub consecutive void method calls:
doThrow(new RuntimeException()).doNothing().doThrow(...).doNothing().when(mMockedObject).doCommit();
thanks Igor!
Reading Stubbing Consecutive Calls doco, something like this might do it:
when(mMockedObject.doCommit())
.thenThrow(new RuntimeException())
.thenCallRealMethod()
.thenThrow(new RuntimeException())
.thenCallRealMethod();
If you don't want to actually call the underlying method then you should use thenAnswer instead of thenCallRealMethod method and provide an empty stub imlementation.

Organizing unit test within a test class

Suppose I have several unit tests in a test class ([TestClass] in VSUnit in my case). I'm trying to test just one thing in each test (doesn't mean just one Assert though). Imagine there's one test (e.g. Test_MethodA() ) that tests a method used in other tests as well. I do not want to put an assert on this method in other tests that use it to avoid duplicity/maintainability issues so I have the assert in only this one test. Now when this test fails, all tests that depend on correct execution of that tested method fail as well. I want to be able to locate the problem faster so I want to be somehow pointed to Test_MethodA. It would e.g. help if I could make some of the tests in the test class execute in a particular order and when they fail I'd start looking for cause of the failure in the first failing test. Do you have any idea how to do this?
Edit: By suggesting that a solution would be to execute the tests in a particular order I have probably went too far and in the wrong direction. I don't care about the order of the tests. It's just that some of the tests will always fail if a prequisite isn't valid. E.g. I have a test class that tests a DAO class (ok, probably not a UNIT test, but there's logic in the database stored procedures that needs to be tested but that's not the point here I think). I need to insert some records into a table in order to test that a method responsible for retrieving the records (let's call it GetAll()) gets them all in the correct order e.g. I do the insert by using a method on the DAO class. Let's call it Insert(). I have tests in place that verify that the Insert() method works as expected. Now I want to test the GetAll() method. In order to get the database in a desired state I use the Insert() method. If Insert() doesn't work, most tests for GetAll() will fail. I'd prefer to mark the tests that can't pass because Insert() doesn't work as inconclusive rather than failed. It would ease finding the cause of the problem if I know which method/test to look into first.
You can't (and shouldn't) execute unit tests in a specific order. The underlying reason for this is to prevent Interacting Tests - I realize that your motivation for requesting such a feature is different, but that's the reason why unit test frameworks don't allow you to order tests. In fact, last time I checked, xUnit.net even randomizes the order.
One could argue that the fact that some of your tests depend on a different method call on the same class is a symptom of tight coupling, but that's not always the case (state machines come to mind).
However, if possible, consider using a Back Door instead of the other method in question.
If you can't do either that or decouple the interdependency (e.g. by making the first method virtual and using the Extract and Override technique), you will have to live with it.
Here's an example:
public class MyClass
{
public virtual void FirstMethod() { // do something... }
public void SecondMethod() {}
}
Since FirstMethod is virtual, you can derive from MyClass and override its behavior. You can also use a dynamic mock to do that for you. With Moq, it would look like this:
var sutStub = new Mock<MyClass>();
// by default, Moq overrides all virtual methods without calling base
// Now invoke both methods in sequence:
sutStub.Object.FirstMethod(); // overriden by Moq, so it does nothing
sutSutb.Object.SecondMethod();
I think I would indeed have the assertion on the method_A() result in every tests relying on its result, even if this introduces some duplication. Then I would use the assertion message to point to the method_A() failure.
assert("method_A() returned true", true, rc);
Perhaps will I end extracting the method_A() call and the assertion into an helper function to remove the duplication.
Now let's imagine method_A() queries an object and returns it, or NULL when no object is found. Then this assertion is a guard ; and it is necessary with languages suchas C, C++ that do not have NullPointerException.
I'm afraid you can't do this. The only solution is to redesign your code and break it up into smaller methods so that unit tests can call these one by one. Of course this isn't always desirable.
With Visual Studio you can order your tests: see here. But I'd like to advise you to stay away from this technique as much as possible: unit tests are meant to be run anywhere, anytime and in every order.
EDIT: why is this a problem for you? All failing tests point to the same method anyway...