I am getting InvalidUseOfMatchersException on a different test than the one using Matchers
The below two tests are running fine individually but when running together, after the first test passes successfully, second test is failing and throwing InvalidUseOfMatchersException pointing to first test
#Test(expected = InputException.class)
public void shouldThrowExceptionWhenInputNull() {
calculator.calculateA(any(), any(), any(),eq(null));
}
#Test
public void testCalculateB() {
assertTrue(BigDecimal.valueOf(8000).compareTo(calculator.calculateB(12)) == 0);
}
This is the exception in stack trace
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
TestClass.shouldThrowExceptionWhenInputNull
According to the exception, first test should fail but its passing and second test is failing. Individually both these tests are passing successfully
calculator.calculateA(any(), any(), any(), eq(null));
This isn't a valid use of Matchers. Mockito only uses any and eq when used with when or verify, as a means of matching invocations that tell Mockito what to return or what calls should have been recorded. You'll need to call calculateA with specific values, such as calculator.calculateA(1, 2, 3, null);.
Mockito matchers work via side effects, so the only time that Mockito can throw an exception is the next time you interact with Mockito. This might be another method, but you can help ensure that those are local by using MockitoRule, MockitoJUnitRunner, or by adding a call to validateMockitoUsage from an #After method:
#After public void validateMockito() {
Mockito.validateMockitoUsage();
}
Related
I have my ServiveImpl class, which has public methods to create and delete index from AEM to Solr. How can we handle the Junit for these void methods using Mockito? Any pointers will be help. Mainly for testing integration with Solr
In this case, your JUnit wouldn't really make any difference other than giving you some test coverage.
The reason behind writing a Junit is to ensure that a method returns a result, or throws an exception. With a void method, the only thing that can be tested is that the method executes.
To solve this, it would be good to at least return a boolean value. Without this, you can never be sure whether the index was really deleted or not.
So the suggestion here would be-
Update the method to ensure the correct error handling takes place.
Based on the method execution, return a boolean value at least. This will not have any impact on your project because the method was void anyway and no calls would be impacted.
In your Junit, assert the returned value as true or false, or just use the assertTrue method.
boolean deleteIndex(String indexName) {
if (deleted) {
return true;
} else {
return false;
}
}
JUnit-
#InjectMocks
private ServiveImpl service = new ServiveImpl();
#Test
public void testIndexDeletion() {
boolean indexDeleted = ServiveImpl.deleteIndex("someIndex");
assertTrue(indexDeleted);
}
I have a simple unit test which asserts on an object instance of Try from the vavr library.
#Test
public void testFoo()
{
final Try<Foo> result = createMyFooInstance();
assertThat(result.isSuccess()).isTrue();
}
My question focuses on the formulation of the test assertion.
Semantically I want to have "if foo is success, all fine, otherwise, throw the encapsulated exception". The latter one is important so that I can see the error cause directly in the JUnit output.
Is there any convenient API that I can use to nicely formulate that semantics?
You could use
#Test
public void testFoo() {
final Try<Foo> result = createMyFooInstance();
result.get();
}
In case when result is a Failure, result.get() will throw the wrapped exception. In case when result is a Success, it will succeed.
Though this solution doesn't contain explicit assertions, it will implicitly fail the cases when the result is a Failure.
If you prefer to have an assertion failed instead of a test failed with exception, you could also use:
#Test
public void testFoo() {
final Try<Foo> result = createMyFooInstance();
assertThatCode(result::get).doesNotThrowAnyException();
}
How do I test if an assertion is thrown by the method under test using junit? Heres the method I'm testing:
public int f(int i){
assert i > 0;
return i;
}
I'm using junit 4.12.
You can test it by providing parameter in #Test annotation:
#Test(expected = AssertionError.class)
public void shouldThrowExceptionWhenIncorrectInput() {
f(-3);
}
This will check if the AssertException is thrown.
However, if you want to ensure that this function wont be run with incorrect parameters, you have to be aware that assertions can be turned off by running java with -da parameters.
To ensure that exception is thrown I would suggest throwing IllegalArgumentException inside some validation method, and to provide it with proper message. Then you will be sure that this will always throw exception when incorrect parameters are provided.
In my webdriver script I have the three methods
setup, test and tearDown
following the junit convention.
In the test method I have few asserts like this
#Test
public void testStudentHome() throws Exception {
String classCode = "I6OWW";
Utilities.studentSignin(driver, baseUrl);
assertEquals(true, sth.openNotification());
assertEquals("My Scores", sth.myScores(true));
}
The sth is the PageObject on which I am performing the tests and that I have created in the setup method.
I am calling all these three methods from a main method like this:
public static void main(String[] args) {
StudentHomeTest sht = new StudentHomeTest();
try {
sht.setup();
sht.testStudentHome();
sht.tearDown();
} catch (Exception ex) {
Logger.getLogger(StudentHomeTest.class.getName()).log(Level.SEVERE, null, ex);
sht.tearDown();
}
}
Now while running the test if some assertion fails the test method should (this is what I expect) throw an exception and the main method should call the tearDown method. But this does not happen. and the browser window continues to stay there.
I am using the netbeans ide for running the test.
following the junit convention
If you follow the jUnit convention, then you will know that teardown methods belong in the #After method as this method will always run after your tests.
create a new method with the #After jUnit annotation.
#After
public void tearDown() {
sht.tearDown();
}
Edit
You know what, I believe that you are running into a classic issue of assertEquals in jUnit.
Stolen from this answer...:
JUnit calls the .equals() method to determine equality in the method assertEquals(Object o1, Object o2).
So, you are definitely safe using assertEquals(string1, string2). (Because Strings are Objects)
--
Instead of using assertEquals on these calls, use assertTrue() instead.
assertTrue(sth.openNotification());
assertTrue("My Scores".equals(sth.myScores(true)));
AssertionError doesn't extend Exception - it's a Throwable.
But in any case, you should have
try {
sht.setup();
sht.testStudentHome();
} finally {
sht.tearDown();
}
No need for a catch block. main can throw Exception.
If writing a Java unit test with mocking using JMock, should we use
Mockery context = new Mockery()
or
Mockery context = new JUnit4Mockery()
What is the difference between the two, and when should we use which?
#Rhys It's not the JUnit4Mockery that replaces the need to call assertIsSatisfied, its the JMock.class (combined with the #RunWith). You wont need to call assertIsSatisfied when you create a regular Mockery.
The JUnit4Mockery translates errors.
By default, expectation exceptions are reported in Junit as ExpectationError, so for example, using
Mockery context = new Mockery();
you'll get
unexpected invocation: bar.bar()
no expectations specified: did you...
- forget to start an expectation with a cardinality clause?
- call a mocked method to specify the parameter of an expectation?
and using,
Mockery context = new JUnit4Mockery();
you'll get
java.lang.AssertionError: unexpected invocation: bar.bar()
no expectations specified: did you...
- forget to start an expectation with a cardinality clause?
- call a mocked method to specify the parameter of an expectation?
what happened before this: nothing!
The JUnit4Mockery converted the ExpectationError to an java.lang.AssertionError which JUnit deals with. Net result is that it'll show up in your JUnit report as an failure (using JUnit4Mockery) rather than an error.
When using JMock with JUnit 4, you can avoid some boilerplate code by taking advantage of the JMock test runner. When you do this, you must use the JUnit4Mockery instead of the regular Mockery.
Here is how you'd structure a JUnit 4 test:
#RunWith(JMock.class)
public void SomeTest() {
Mockery context = new JUnit4Mockery();
}
The main advantage is there is no need to call assertIsSatisfied in each test, it is called automatically after each test.
Better yet, per http://incubator.apache.org/isis/core/testsupport/apidocs/org/jmock/integration/junit4/JUnitRuleMockery.html use #Rule and avoid #RunWith which you might need for some other system:
public class ATestWithSatisfiedExpectations {
#Rule
public final JUnitRuleMockery context = new JUnitRuleMockery();
private final Runnable runnable = context.mock(Runnable.class);
#Test
public void doesSatisfyExpectations() {
context.checking(new Expectations() {
{
oneOf(runnable).run();
}
});
runnable.run();
}
}