Difference between #TestSubject and #InjectMocks? - java

While learning Mockito I found two different annotations #TestSubject and #InjectMocks at below references.
#TestSubject Ref#InjectMocks Ref
#InjectMocks annotation is working absolutely fine as explained in tutorial but #TestSubject doesn't work rather its displaying error.
I'm getting TestSubject cannot be resolved to a type error for #TestSubject annotation in the below code snippet however I have done proper setup (including Junit & Mockito jar files in the build path).
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.infosys.junitinteg.action.MathApplication;
import com.infosys.junitinteg.service.CalculatorService;
#RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
// #TestSubject annotation is used to identify class which is going to use
// the mock object
#TestSubject
MathApplication mathApplication = new MathApplication();
// #Mock annotation is used to create the mock object to be injected
#Mock
CalculatorService calcService;
#Test(expected = RuntimeException.class)
public void testAdd() {
// add the behavior to throw exception
Mockito.doThrow(new RuntimeException("Add operation not implemented")).when(calcService).add(10.0, 20.0);
// test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0), 30.0, 0);
}
}
I have two questions here.
1. Has some one encountered similar issue? If yes then what was the root cause and solution?
2. If it's working fine then what is the difference between #TestSubject and #InjectMocks annotations?

#TestSubject is the annotation of EasyMock that does the same like Mockito's #InjectMocks. If you're using Mockito then you have to use #InjectMocks.

Related

Powermock throws InvalidUseOfMatchersException when mocking private method

I'm new to Powermock. Yesterday I watched a video about using Powermock, I follow their code and have a demo test program below. When I run the test
package myPackage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
public class Test1{
#Test
public void testPrivateMethod() throws Exception {
DemoService mockDemoService = PowerMockito.spy(new DemoService());
PowerMockito.when(
mockDemoService,
"privateMethod",
ArgumentMatchers.any(String.class)
).then(invocation -> invocation.getArgument(0) + "_private_mock");
Assert.assertEquals(mockDemoService.dependentMethod("LoveTest"), "3000LoveTest_private_mock");
}
}
class DemoService {
private String privateMethod(String input) {
return input + "_private";
}
public String dependentMethod(String input) {
return 3000 + privateMethod(input);
}
}
It throw exception in the log below
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at myPackage.Test1.testPrivateMethod(Test1.java:19)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
I have some basic knowledge about Mockito, the code is somewhat similar to Mockito unit test (Mockito.spy and Mockito.when) but not work as expected. I don't know what's wrong with the code, why the exception InvalidUseOfMatchersException is thrown. Please help me, thank you.
Your code is missing #PrepareForTest. Powermock has to manipulate the byte-code of target mocking class, so you have to provide a path to it.
#RunWith(PowerMockRunner.class)
#PrepareForTest(DemoService.class)
public class Test1{
...
here ArgumentMatchers.any(String.class)
instead use ArgumentMatchers.anyString()

Junit 5 and Mockito 3: UnnecessaryStubbingException not thrown when injecting #Mock's through constructor

Looking at the two test classes below I assume the same behavior from them: to have an UnnecessaryStubbingException thrown. However MyTest2 does not. The MockitoExtension class should have strictness set to strict stubs by default. I can't seem to find any documented information about this behavior and I really want to understand it.
I prefer to write my tests as MyTest2 because I like to have final fields wherever possible, though I also really enjoy the strict stubs check done by Mockito.. Please help my understand the difference between the two tests.
package example;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
#ExtendWith(MockitoExtension.class)
class MyTest {
#Mock
List<Integer> integerList;
#Test
void test() {
Mockito.when(integerList.size()).thenReturn(10);
System.out.println("Do something not involving list");
Assertions.assertTrue(true);
}
}
#ExtendWith(MockitoExtension.class)
class MyTest2 {
final List<Integer> integerList;
MyTest2(#Mock List<Integer> integerList) {
this.integerList = integerList;
}
#Test
void test() {
Mockito.when(integerList.size()).thenReturn(10);
System.out.println("Do something not involving list");
Assertions.assertTrue(true);
}
}
I found the reason in the mockito documentation:
Mockito JUnit Runner triggers UnnecessaryStubbingException only when none of the test methods use the stubbings. This means that it is ok to put default stubbing in a 'setup' method or in test class constructor. That default stubbing needs to be used at least once by one of the test methods.
If you do not want the exception to be thrown for the MyTest class, you can use Mockito.lenient or MockitoSettings. But I guess it is not possible to activate the exception for the MyTest2 class.

CdiUnit test with Junit #Rule is impossible because of a public private field paradox

The following snippet is enough to reproduce my problem:
Either I set the thrown attribute public and get the error org.jboss.weld.exceptions.DefinitionException: WELD-000075: Normal scoped managed bean implementation class has a public field
Or I remove the public modifier and get the error org.junit.internal.runners.rules.ValidationError: The #Rule 'thrown' must be public.
I also tried to let the public modifier in place and to add the #Dependent annotation scope on the class, but got error org.jboss.weld.exceptions.DefinitionException: WELD-000046: At most one scope may be specified on [EnhancedAnnotatedTypeImpl] public #Dependent #ApplicationScoped #RunWith
I stripped out all unnecessary code, but this is quite a complex unit test with mock, service injection through CDI and some test methods thar are expected to throw an exception.
import org.jglue.cdiunit.CdiRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
#RunWith(CdiRunner.class)
public class FooBarTest {
#Rule
public ExpectedException thrown = ExpectedException.none();
#Test
public void test() {
}
}
So my problem is that on one hand Weld wants all fields to not be public because it will not be able to proxify the class otherwise, and on the other hand, JUnit want Rule fields to be public because it is using reflection to access them and does not want to use the setAccessible(true) method because of the cases where the security manager is active. How to deal with that paradox?
NB: I also found a hint comments to this answer, stating that
You can also annotate a method with #Rule, so this would avoid the problem
But I could not found any example of junit test with a #Rule annotation on a method, I plan to ask a separate question about this.
I found out how to solve the problem. For future reference, here is a snippet that works, hope this will help other people.
import org.jglue.cdiunit.CdiRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
#RunWith(CdiRunner.class)
public class FooBarTest {
private ExpectedException thrown = ExpectedException.none();
#Rule
public ExpectedException getThrown() {
return thrown;
}
#Test
public void test() {
thrown.expect(ArithmeticException.class);
int i = 1 / 0;
}
}

PowerMock not stubbing static method properly?

I'm trying to write a VERY simple test, using powermock and Robolectric. Here's my code:
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.robolectric.RobolectricTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(RobolectricTestRunner.class)
#PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
#PrepareForTest(BadStaticClass.class)
public class SomeActivityTest {
#Test
public void testSomething() {
PowerMockito.mockStatic(BadStaticClass.class);
Mockito.when(BadStaticClass.dontWantThisMethod()).thenReturn(false);
new SomeActivity().usesStatic();
}
}
Basically, i have a class, "SomeActivity", and it has a method that makes a call to BadStaticClass.dontWantThisMethod(). i want that static method to be stubbed out.
why is my code not working?
i kept getting errors like:
you are trying to stub a final method, you naughty developer!
which, i thought the whole point of PowerMock was to not see that.
According to the PowerMock API you have to include #RunWith(PowerMockRunner.class) for certain versions of JUnit, etc. However you also need to be using #RunWith(RobolectricTestRunner.class) and cannot specify more than one #RunWith on a Class.
So what to do?
I suspect you can keep your code above and introduce a JUnit #Rule (see: PowerMockRule docs) and also described in this similar post. Just be sure you check the versions of the Jars you are using so that they match those described in that other SO post. All too often things just won't work unless you get compatible versions, and it's not always obvious what versions are compatible.

Using assertArrayEquals in unit tests

My intention is to use assertArrayEquals(int[], int[]) JUnit method described in the API for verification of one method in my class.
But Eclipse shows me the error message that it can't recognize such a method. Those two imports are in place:
import java.util.Arrays;
import junit.framework.TestCase;
Did I miss something?
This would work with JUnit 5:
import static org.junit.jupiter.api.Assertions.*;
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
This should work with JUnit 4:
import static org.junit.Assert.*;
import org.junit.Test;
public class JUnitTest {
/** Have JUnit run this test() method. */
#Test
public void test() throws Exception {
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
}
}
This is the same for the old JUnit framework (JUnit 3):
import junit.framework.TestCase;
public class JUnitTest extends TestCase {
public void test() {
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
}
}
Note the difference: no Annotations and the test class is a subclass of TestCase (which implements the static assert methods).
This could be useful if you want to use just assertEquals without depending on your Junit version
assertTrue(Arrays.equals(expected, actual));
Try to add:
import static org.junit.Assert.*;
assertArrayEquals is a static method.
If you are writing JUnit 3.x style tests which extend TestCase, then you don't need to use the Assert qualifier - TestCase extends Assert itself and so these methods are available without the qualifier.
If you use JUnit 4 annotations, avoiding the TestCase base class, then the Assert qualifier is needed, as well as the import org.junit.Assert. You can use a static import to avoid the qualifier in these cases, but these are considered poor style by some.

Categories