Simple Junit class is not calling the #Before method [duplicate] - java

I have the following code:
#BeforeClass
public static void setUpOnce() throws InterruptedException {
fail("LOL");
}
And various other methods that are either #Before, #After, #Test or #AfterClass methods.
The test doesn't fail on start up as it seems it should. Can someone help me please?
I have JUnit 4.5
The method is failing in an immediate call to setUp() which is annotated as #before.
Class def is :
public class myTests extends TestCase {

do NOT extend TestCase AND use annotations at the same time!
If you need to create a test suite with annotations, use the RunWith annotation like:
#RunWith(Suite.class)
#Suite.SuiteClasses({ MyTests.class, OtherTest.class })
public class AllTests {
// empty
}
public class MyTests { // no extends here
#BeforeClass
public static void setUpOnce() throws InterruptedException {
...
#Test
...
(by convention: class names with uppercase letter)

the method must be static and not directly call fail (otherwise the other methods won't be executed).
The following class shows all the standard JUnit 4 method types:
public class Sample {
#BeforeClass
public static void beforeClass() {
System.out.println("#BeforeClass");
}
#Before
public void before() {
System.out.println("#Before");
}
#Test
public void test() {
System.out.println("#Test");
}
#After
public void after() {
System.out.println("#After");
}
#AfterClass
public static void afterClass() {
System.out.println("#AfterClass");
}
}
and the ouput is (not surprisingly):
#BeforeClass
#Before
#Test
#After
#AfterClass

Make sure you imported #Test from the correct package.
Correct package: org.junit.Test
Incorrect pacakge: org.junit.jupiter.api.Test
Please note that this is a solution for: If your #Before, #Atter, etc did not get called at all.

Make sure that :
Your test class doesn't inherits from TestCase
The #BeforeClass method is static
You don't have more than one #BeforeClass method in test class hierarchy (only the most specialized #BeforeClass method will be executed)

Check your imports.
#Before
#After
#BeforeClass (this should be static)
#AfterClass (this should be static)
and #Test annotations should import from same path.

In order that the before annotated function will run , I had to do the following:
If you use Maven , add a dependency to Junit 4.11+:
<properties>
<version.java>1.7</version.java>
<version.log4j>1.2.13</version.log4j>
<version.mockito>1.9.0</version.mockito>
<version.power-mockito>1.4.12</version.power-mockito>
<version.junit>4.11</version.junit>
<version.power-mockito>1.4.12</version.power-mockito>
</properties>
and the dependency:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${version.junit}</version>
<scope>test</scope>
</dependency>
.
.
.
</dependencies>
Make sure your Junit Test class is not extending The TestCase class, since this will cause overlapping with Older version:
public class TuxedoExceptionMapperTest{
protected TuxedoExceptionMapper subject;
#Before
public void before() throws Exception {
subject = TuxedoExceptionMapper.getInstance();
System.out.println("Start");
MockitoAnnotations.initMocks(this);
}
}

Related

How to do a BeforeEach on all of my integration test files

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
}

Can I exclude an individual test from #BeforeEach in JUnit5?

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() {}
}
}

Grails JUnit Test case, doesn't execute method marked with #BeforeClass annotation

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.

Using PowerMockRunner with Junit Test Suite

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.

mock instance is null after #Mock annotation

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.

Categories

Resources