Equivalent of never(mock) in JMockit - jmockit

I'm migrating some test cases from JMock to JMockit. It's been a pleasant journey so far but there's one feature from JMock that I'm not able to find in JMockit (version 0.999.17)
I want to check that a mock is never called (any method).
With JMock, all I needed is the following in my Expectations block:
never(mock)
Is it feasible somehow with JMockit?
EDIT:
I might have found a solution but it's not very explicit.
If I put any method of this mock with times =0 in my Expectations block then this mock becomes strict and I believe any method called would trigger an exception.

Try an empty full verification block, it should verify that no invocations occurred on any given mocks:
#Test
public void someTest(#Mocked SomeType mock)
{
// Record expectations on other mocked types...
// Exercise the tested code...
new FullVerifications(mock) {};
}

Related

Mockito - Is it possible to deep mock a void method call to do nothing?

I wanted to know if it is possible to "deep mock" a void method call without breaking out the call chain, using Mockito.
This is an example for the original call I want to mock:
obj.getSomething().add(3);
where "add"'s return type is void.
I tried:
doNothing().when(obj).getSomething().add(3)
and:
doNothing().when(obj.getSomething()).add(3) //wont work since "when" expects a mock.
I also failed using Mockito.when(...) since it does not work with void methods.
I do not want to break the call up since it will be very cumbersome for fluent API calls that are much longer.
Is there an official solution / workaround for this scenario?
Thanks :)
If the value returned by getSomething is not a mock, it won't work.
Return value of getSomething should be a mock and it will allow to assign mock behavior for that value.
Something someMock = mock(Something.class);
when(obj.getSomething()).thenReturn(someMock);
doNothing().when(someMock).add(3);

how to mock calling kotlin.system.exitProcess

I want to test some code that uses 3rd party code that calls kotlin.system.exitProcess(), defined as follows in the standard lib:
#kotlin.internal.InlineOnly
public inline fun exitProcess(status: Int): Nothing {
System.exit(status)
throw RuntimeException("System.exit returned normally, while it was supposed to halt JVM.")
}
When exitProcess() is called, the JVM stops and further testing is impossible. I didn't manage to mock calls to exitProcess() with mockk. Is it possible?
Some further information:
The 3rd party lib is Clikt (https://ajalt.github.io/clikt/), a nice library for building a command line interface. A Clikt application parses the command line, and exits if this fails. This may be one of the rare reasons, where calling System.exit is OK. Surely there are more testable solutions, but anyway, when working with 3rd party libs, arguing what could be better done in the lib is obsolete.
What I actually want to test is, that my application writes the expected usage message when called with --help or wrong arguments.
I also tried to mock the call to System.exit() this way:
mockkStatic("java.lang.System")
every { System.exit(any()) }.throws(RuntimeException("blubb"))
which leads to another problem, als all calls to System are mocked then:
io.mockk.MockKException: every/verify {} block were run several times. Recorded calls count differ between runs
Round 1: class java.lang.System.getProperty(kotlin.ignore.old.metadata), class java.lang.System.exit(-630127373)
Round 2: class java.lang.System.exit(158522875)
Funnily enough, I managed to test this in Java with jmockit, like this:
public class MainTestJ {
private ByteArrayOutputStream consoleOut;
#BeforeEach
public void mockConsole() {
consoleOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(consoleOut));
}
#Test
public void can_mock_exit() {
new MockUp<System>() {
#Mock
public void exit(int exitCode) {
System.out.println("exit called");
}
};
assertThatThrownBy(() -> {
new Main().main(new String[] { "--help" });
}).isInstanceOf(RuntimeException.class);
assertThat(consoleOut.toString()).startsWith("Usage: bla bla ...");
}
}
I played with this for a while attempting to get it to work but unfortunately it is not possible. There are several difficulties with mocking this function; that it is a Top Level function and that it returns Nothing. Each of these can be overcome, but what makes it impossible is that the function is inlined. Inlined kotlin functions do not produce methods in the bytecode, it is as it says on the tin, inlined. The trouble is that Mockk and other mocking libraries use bytecode instructions when mocking. Refer to this issue for more information.
Your best alternative is not to attempt to mock this function at all, but instead mock the call into the third party library you are using. After all, you should not be testing this third party code, only your own code. Better yet, maybe you should seek an alternative library. As has already been stated in the comments, a third party library should not be exiting the process, this should be left up to the client code.

Calling OCMStub and OCMReject on the same method

I've been attempting to write some fail fast tests using OCMReject. However I've found that if OCMStub is used in conjunction with OCMReject, this test will pass
id _mockModel = OCMProtocolMock( #protocol( CTPrefModelProtocol));
//It doesn't seem to matter what order these two are in, the test behaves the same
OCMStub([_mockModel getPreferences]);
OCMReject([_mockModel getPreferences]);
[_mockModel getPreferences];
Even though it should clearly fail because I'm calling the function that I've set in the OCMReject method.
I realise I can just stub getPreferences whenever I'm expecting a result from it and remove it from this test, but largely that means if I've set a stub on getPreferences in my setUp method, any test that calls OCMReject([_mockModel getPreferences]) will just be ignored.
Why am I not able to use OCMStub and OCMReject together? Is it because OCMStub alters getPreferences somehow and as a result whenever I call this method, it actually calls some other method instead?
So apparently I can't read. Reading through the OCMock 3 Documentation, under the limitations heading 10.2
Setting up expect after stub on the same method does not work
id mock = OCMStrictClassMock([SomeClass class]);
OCMStub([mock someMethod]).andReturn(#"a string");
OCMExpect([mock someMethod]);
/* run code under test */
OCMVerifyAll(mock); // will complain that someMethod has not been called
The code above first sets up a stub for someMethod and afterwards an
expectation for the same method. Due to the way mock objects are
currently implemented any calls to someMethod are handled by the stub.
This means that even if the method is called the verify fails. It is
possible to avoid this problem by adding andReturn to the expect
statement. You can also set up a stub after the expect.
I suspect this same limitation exists for OCMReject as well. Hopefully this helps equally blind people like myself. A link to the documentation for the lazy.

How do I mark tests as Passed/Skipped/Ignored in serenity?

I keep getting phantomjs error - unreachablebrowserexception.
I want to mark the test as skipped or passed in the catch block of this managed exception. How do I do that?
You can use JUnit's Assume class at the beginning of your test to mark the test as ignored/skipped based on a condition.
For example:
#Test
public void myTest() {
Assume.assumeTrue(yourBooleanCondition);
// continue your test steps...
}
You can read about its different applications here.
However, being able to mark a failed test as passed is against the test mantra and defeats the purpose of developing such code entirely. I do not know any framework that would allow you to do that. If you absolutely have to, my guess is to fiddle with the results.

Unable to figure out rhino mocks issue

In a method in presenter,I expect a method of view to be called.This method is also passed data extracted from a service method(which is not mocked).This service method basically gets data from database and returns List(using LINQ to SQL).Now, when I write this in the test
List<customers> cus = expecteddata;
view.AssertWasCalled(v => v.InitializeCustomersForSelectedCity(cus));
Rhino.Mocks.Exceptions.ExpectationViolationException: ICustomerListView.InitializeCustomersForSelectedCity(System.Collections.Generic.List`1[DAL.Customer]); Expected #1, Actual #0.
The code which I am testing in presenter
public void HandleSelectedCity(int City)
{
selectedCity = City ;
_custometListForm.InitializeCustomersForSelectedCity(_CustomerListService.GetActiveCustomersForSelectedCity(selectedCity));
}
When I ignore arguments, test works fine
What could be the issue?
You assertion creates an expectation based on cus, a variable defined in the unit test. However, when InitializeCustomersForSelectedCity is invoked, it's being invoked with the result of GetActiveCustomersForSelectedCity - a different instance of List<customers>.
Expectations setups basically perform an object.Equals operation on the expected instance and the actual instance. In your case, they are different, and the expectaction is not satisfied.
Either you need to loosen your expectation to accept any List<customers>, or you need to mock GetActiveCustomersForSelectedCity as well so that you can define the returned result from the unit test.