I have a bit of code I'd like to run in every #BeforeEach of all my integration tests files. Basically the code I need to add is the following :
#MockBean
RequestInterceptor interceptor; // I NEED THIS
#BeforeEach
public void initTest() throws Exception {
Mockito.when(interceptor.preHandle(any(), any(), any())).thenReturn(true); // AND THIS
}
Is there a way to avoid duplicating this part in every files ? Maybe I can create a test configuration file and use an annotation in my test files. As I am very new to java spring boot I would appreciate some help. Thanks.
You can create super class e.g. BaseTest and move this code there. And then every your test should just extend BaseTest. Even more you can set all Annotation in this class. E.g.:
#AutoConfigureMockMvc
#MockitoSettings(strictness = Strictness.STRICT_STUBS)
#ExtendWith(MockitoExtension.class)
#ExtendWith(SpringExtension.class)
#ActiveProfiles("test")
#SpringBootTest
public class BaseTest {
#MockBean
RequestInterceptor interceptor; // I NEED THIS
#BeforeEach
public void initTest() throws Exception {
Mockito.when(interceptor.preHandle(any(), any(), any())).thenReturn(true); // AND THIS
}
}
And then all your tests:
class MeasurementsServiceTest extends BaseTest {
//test methods here
}
Well you can make a parent base class that would have the BeforeEach method and then just inherit that class on all of the other ones
public class BaseTestClass {
#BeforeEach
public void setUp(){
System.out.println("Base Test Class");
}
}
public class InheritsFromBase extends BaseTestClass {
// here goes test code
}
Is it possible to exclude an individual test from #BeforeEach in JUnit5?
Kindly guide me for this.
Thank you
You could use TestInfo and write this condition by inspecting the test name:
#BeforeEach
void init(TestInfo info) {
if (info.getDisplayName().equals("mySpecialTestName") {
return; // skip #BeforeEach in mySpecialTestName test
}
}
but it would be cleaner to move the tests that don't need #BeforeEach to a separate class.
You can move the tests that require the before-each behaviour into an inner ˋ#Nested´ subclass and put the before-each method there.
public class MyClassTest {
#Test
void test1(){}
#Nested
private class NestedTestBlock {
#BeforeEach
void beforeEach(){}
#Test
void test2() {}
#Test
void test3() {}
}
}
Here's my code below, testSample() gets executed successfully. Please suggest what could possibly be wrong
class DataServiceTest extends GrailsUnitTestCase{
#BeforeClass
static void onceExecutedBeforeAll() {
println(" Print before Start Test Cases");
}
#Test
public void testSample(){
println(" Inside Sample");
}
}
You can't extend a TestCase and use annotations at the same time. If you want to create a test suite with annotations, you can use #RunWith annotation:
#RunWith(Suite.class)
#Suite.SuiteClasses({ DataServiceTest.class, OtherTest.class })
public class AllTests {
// empty
}
public class DataServiceTest { // no extends here
#BeforeClass
static void onceExecutedBeforeAll() {
println(" Print before Start Test Cases");
}
#Test
public void testSample(){
println(" Inside Sample");
}
}
Another option using JUnit could be annotating the method with #Before and removing extends GrailsUnitTestCase from the class.
I'm trying to create a Junit test suite along with using PowerMockRunner but it does not work.
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(MainTest.class)
#Suite.SuiteClasses({ MainTest.Class1Test.class })
#PrepareForTest({
StaticFieldsProvider.class
})
public class MainTest extends Suite {
public MainTest(Class<?> klass, RunnerBuilder builder)
throws InitializationError {
super(klass, builder);
}
public static class TestBase {
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(StaticFieldsProvider.class);
}
}
public static class Class1Test extends TestBase {
#Before
public void setUp() {
super.setUp();
}
#Test
public void test(){
assertTrue(true);
}
}
}
When I try to run, it fails with error -
java.lang.IllegalArgumentException: Test class can only have one constructor
at org.junit.runners.model.TestClass.(TestClass.java:40)
Any suggestions on how to use PowerMockRunner in above case?
Thanks
This is an old question, so we may get no resolution on whether or not this solution works for the OP; but this might work (I can't verify without having access to StaticFieldsProvider, but it works if I swap that out with one of my own classes). I would love for someone to edit and add more explanation as to why this works:
#RunWith(PowerMockRunner.class)
// * Delegate to Suite.class instead of MainTest.class *
#PowerMockRunnerDelegate(Suite.class)
#Suite.SuiteClasses({ MainTest.Class1Test.class })
#PrepareForTest({
StaticFieldsProvider.class
})
// * Don't extend Suite *
public class MainTest {
// * Remove constructor *
public static class TestBase {
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(StaticFieldsProvider.class);
}
}
public static class Class1Test extends TestBase {
#Before
public void setUp() {
super.setUp();
}
#Test
public void test(){
assertTrue(true);
}
}
}
In case it helps someone else, I had a slightly different scenario in that only a couple of the classes in my suite need PowerMockRunner (and don't mock out the same thing, so the mock needs to happen in each individual test class instead of in the runner). It appears that as long as I #PrepareForTest in my runner (as above) the classes I will need in some of the test classes, I can still create the mocks in the #Before (or wherever) of the applicable test class. Hope this helps.
You must not extend Suite, because this is a part of JUnit 3 and you are using JUnit 4. (Remove the extends and the constructor.) See the JUnit Wiki for more datails about Suites in JUnit 4.
I try to run this test:
#Mock IRoutingObjHttpClient routingClientMock;
#Mock IRoutingResponseRepository routingResponseRepositoryMock;
#Test
public void testSendRoutingRequest() throws Exception {
CompleteRoutingResponse completeRoutingResponse = new CompleteRoutingResponse();
completeRoutingResponse.regression_latencyMillis = 500L;
Mockito.when(routingClientMock.sendRoutingRequest(any(RoutingRequest.class))).thenReturn(completeRoutingResponse);
RoutingObjHttpClientWithReRun routingObjHttpClientWithReRun = new RoutingObjHttpClientWithReRun
(routingClientMock, routingResponseRepositoryMock);
...
}
but I get NullPointerException for:
Mockito.when(routingClientMock.
what am i missing?
When you want to use the #Mock annotation you should use the MockitoJUnitRunner
#RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
#Mock
private IRoutingObjHttpClient routingClientMock;
#Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
See also this tutorial.
Same problem can occur if you are using Junit5 since there is no more '#RunWith' annotation.
In this case you should annotate your class with:
#ExtendWith(MockitoExtension.class)
public class MyTestClass {
...
You should also import into your dependency (Maven - pom.xml):
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
You have three options for activating the #Mock annotation: MockitoRule, MockitoJUnitRunner, MockitoAnnotations.initMocks(this). IMHO using the MockitoRule is the best one, because it lets you still choose another runner like e.g. Parameterized.
Use the MockitoRule
public class MockitoTest {
#Mock
private IRoutingObjHttpClient routingClientMock;
#Rule
public MockitoRule rule = MockitoJUnit.rule();
#Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
Use the MockitoJUnitRunner
#RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
#Mock
private IRoutingObjHttpClient routingClientMock;
#Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
Call MockitoAnnotations.initMocks(this) explicitly.
This can be done in qn #Before method, in your own runner or in an own rule.
public class MockitoTest {
#Mock
private IRoutingObjHttpClient routingClientMock;
#Before
public void createMocks() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
If you use junit.jupiter with #ExtendWith(MockitoExtension.class) for test class but mocks are null, ensure that #Test annotation is imported from
import org.junit.jupiter.api.Test;
instead of org.junit.Test;
What solved this issue for me (combination of answers above and my own additions):
MockitoAnnotations.initMocks(this); in the #Before method
Test class must be public
Test methods must be public
import org.junit.Test; instead of import org.junit.jupiter.api.Test;
When doing command + N --> Test... in Intellij it generates (as a default at least) some boilerplate that did not work in my case.
For me, even after adding #RunWith(MockitoJUnitRunner.class) it was not working.
Turned out, I had made the silly mistake of importing #Test from
import org.junit.jupiter.api.Test;
instead of
import org.junit.Test;
After correcting it, it worked!
It can also be an import problem, so make sure you have the appropriate imported package.
For example, the "org.easymock" package also does have an annotation called #Mock, which of course, won't work with Mockito specific setup.
Add #ExtendWith(MockitoExtension.class) annotation to the test class and it should work given You are using Junit 5+ version.
If you are using older version of Junit use #RunWith(MockitoJUnitRunner.class) annotation.
You should use #RunWith(SpringJUnit4ClassRunner.class) at your class
You have to call MockitoAnnotations.initMocks(this); in #Before method
I had the problem that I declared #Mock MyClass myClass and then tried to mock a behaviour inside my #BeforeAll annotated method:
#Mock
private MyClass myClass;
...
#BeforeAll
public void init()
{
...
Mockito.when(myClass.something()).thenReturn("Not found")
...
}
Apparently init() was executed before the mock initialization of myClass, so myClass == null inside init().
The solution was to change the annotation from #BeforeAll to #BeforeEach.
Try to to check if the method that you are calling is a final method or not.
Mockito cannot mock the final method. https://github.com/mockito/mockito/wiki/FAQ
For me it worked when I added :
At class level:
#RunWith(MockitoJUnitRunner.class).
Inside class:
#Before
public void createMocks() {
MockitoAnnotations.initMocks(this);
}
Junit 5 with InjectMocks. Based on above suggestion https://stackoverflow.com/a/55616702/2643815
#ExtendWith(MockitoExtension.class)
public class MyClientTest {
#Mock
Environment environment;
#Mock
ClassCreator classCreator;
#InjectMocks
MyClient myClient;
#Test
public void mytest() {
myClient = new MyClient(environment, classCreator);
}
}
For me adding the annotation to the class:
#RunWith(MockitoJUnitRunner.class)
and modifying the version of Mockito solved this issue.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
I had the same issue, but I found updating my tests (which were originally written for JUnit 3 and used the legacy setUp() and tearDown() methods) to JUnit 4 and modern annotated fixture methods worked.
Additionally, if you're using the Rule:
#Rule public MockitoRule rule = MockitoJUnit.rule();
Make sure the rule is also on a public class or you will receive the message:
How did getFields return a field we couldn't access?
Found this solution in comments that worked for me. Do this for all the mocks you are creating.
You need to instantiate the routingClientMock e.g.
routingClientMock = Mockito.mock(RoutingObjHtttpClient.class);
My issue was that I was trying to mock an object which was final in my service. Just needed to remove final and it worked.
If you are also using PowerMock then
#RunWith(MockitoJUnitRunner.class)
can be replaced with
#RunWith(PowerMockRunner.class)
This will activate your #Mocks and enable the PowerMock functionality.