JAVA.NET.HTTP.HTTPClient returns InaccessibleObjectException Error Using Junit5+Mockito - java

I am running into the following exception while trying to test my Java application with Junit5 and Mockito.Given below are the exception, code snippet and the dependencies used. Any insight would be highly appreciated.
java.lang.reflect.InaccessibleObjectException: Unable to make protected java.net.http.HttpClient() accessible: module java.net.http does not "opens java.net.http" to unnamed module #131ef10
#RunWith(MockitoJUnitRunner.class)
public class StudentRegisterServiceTest {
#Mock
HttpClient client;
#Mock
HttpRequest request;
#Mock
HttpResponse<String> response;
#Test
public void testPopulateStudentDetails() throws IOException, InterruptedException{
Properties configFile = mock(Properties.class);
StudentRegisterService studentService = new StudentRegisterService();
when(configFile.getProperty(anyString())).thenReturn("");
when(configFile.getProperty(anyString()))
.thenReturn("https://example.com");
when(client.send(any(HttpRequest.class), eq(HttpResponse.BodyHandlers.ofString()))).thenReturn(response);
studentService.populateStudentDetails(studentID, configFile);
}
}
------------
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.1.1</version>
<scope>test</scope>
</dependency>

Related

InvalidTestClassError: Invalid test class. How to test spring boot with maven and #BeforeAll/Class initializator

I have the gradle project where I successfully use tests and try to implement the same solution with maven, but I totally can't execute tests there.
Main problem in that I need to use #BeforeAll/Class annotation and init NOT static method.
In the Gradle this works so:
build.gradle
dependencies {
testImplementation "org.springframework.boot:spring-boot-starter-test:${spring_boot_version}"
implementation 'junit:junit:4.13.1'
....
}
tasks.named('test') {
useJUnitPlatform()
}
test classes:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes = {DeardiaryApplication.class})
#WebAppConfiguration
public abstract class AbstractTest {
protected MockMvc mvc;
private ObjectMapper objectMapper = new ObjectMapper();
#Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
...
}
import org.junit.jupiter.api.*;
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
#TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class DatabaseTest extends AbstractTest {
#Autowired
private ExerciseInterface exerciseService;
#BeforeAll
public void init() {
setUp();
exerciseDto = exerciseService.getByExerciseType(ExerciseTypeEnum.SNATCH).get(0);
}
#Test
....
But in the maven project I received InvalidTestClassError: Invalid test class.
When I use junit.Test instead junit.jupiter.api.Test, the #BeforeAll/Class method nod called, or I received error BeforeAll must be static, etc...
pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.boot.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M8</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
This is all difference - classes implemented in the same way
If you don't want to use the static method for BeforeAll, you need to use the annotation TestInstance(Lifecycle.PER_CLASS)
By default the Junit uses PER_METHOD lifecycle, thus the BeforeAll requires it to be static to ensure it is not instantiated with every method.
The TestInstance(Lifecycle.PER_CLASS) annotation ensures that the lifecycle of the test is per class thus removing the requirement of static BeforeAll.

NoSuchMethodError with spring-webmvc upgrade

We upgraded to spring-webmvc 5.2.3.RELEASE.
This is causing a JUnit to fail.
I think the issue is with the .build() method - it can't be found.
The code:
#RunWith(MockitoJUnitRunner.class)
public class CommunicationDeliveryControllerTest {
#InjectMocks
CommunicationDeliveryController controller = new CommunicationDeliveryController();
#Mock
private RequestHandler requestHandler;
#Mock
private HttpServletRequest httpServletRequest;
private MockMvc mockMvc;
private Gson gson = new Gson();
private CommunicationDeliveryController spiedController;
#Before
public void setup() {
spiedController = spy(controller);
mockMvc = standaloneSetup(spiedController).build();
}
#Test
public void initiateBatchRunTest() throws Exception{
MvcResult result = mockMvc.perform(post("/api/BatchRun").contentType(MediaType.APPLICATION_JSON_VALUE).content(gson.toJson(BulkCommunicationRequestData.getBulkEmailRequestForPositive()))).andReturn();
assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
}
#Test
public void deliverCommunicationTest() throws Exception{
MvcResult result = mockMvc.perform(post("/api/deliverCommunication").contentType(MediaType.APPLICATION_JSON_VALUE).content(gson.toJson(BulkCommunicationRequestData.populateAllEmailDetail()))).andReturn();
assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
}
}
The error:
java.lang.NoSuchMethodError: org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StandaloneConfiguration.getInterceptors()[Ljava/lang/Object;
at company.custcomm.service.communicationdelivery.controllers.CommunicationDeliveryControllerTest.setup(CommunicationDeliveryControllerTest.java:45)
Are there compatibility issues between our versions of spring-webmvc, mockito, and JUnit?
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
I upgrade all spring dependencies to 4.3.18-RELEASE, then there is no error any more.
Is there a specific version of spring-test in your dependencies?
I ran into a similar problem a while ago - turned out that there was a strict version limit for spring-test, and upgrading it to 5.2.3-RELEASE resolved the issue.
If you do not want to change the version of your Junit and spring-webmvc then you can specify spring-test version explicitly in your pom.xml. This works for me.
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.0.RELEASE</version>
<scope>test</scope>
</dependency>

RestAssured- object in body throws Error

My Object which i pass in test
#Data
public class UserRequest {
#JsonProperty("name")
private final String name;
#JsonProperty("surname")
private final String surname;
#JsonProperty("email")
private final String email;
#JsonProperty("iaAdmin")
private final boolean isAdmin;
}
than i have it test
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerIT {
#LocalServerPort
private int port;
#Test
public void testIsCreatingNewUser() throws IOException{
given()
.when()
.body(new UserRequest("asd","sad","asd",false))//.body(TestGenerator.getUserRequest())
.port(port)
.post("/user/" + TestGenerator.randomUUID)
.then()
.statusCode(HttpStatus.SC_CREATED);
}
i got error:
java.util.ServiceConfigurationError: com.fasterxml.jackson.databind.Module: Provider com.fasterxml.jackson.module.kotlin.KotlinModule could not be instantiated
and at the bottom stack
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.DefaultConstructorMarker
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 79 more
What is going on?! Kotlin...i use java with spring boot v2.0 m3
I answer question myself. Thank to #Sebastian Duque comment i add dependencies from
http://www.baeldung.com/spring-boot-kotlin
and it helped...
<!--kotlin/ it needs jackson to map objects-->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jre8</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>2.9.0</version>
</dependency>
but it is strange that Jackson in Spring Boot v2 needs Kotlin dependendecies... I use jackson dependencies from spring-boot starters so i didnt include any jackson.
If you use maven exclude from spring-boot dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.0.M6</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.0.0.M6</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</exclusion>
</exclusions>
</dependency>
For other build tools, update this solution

Test Class unrecognized in Eclipse

I have this class, but eclipse does not recognize it as a test class, so I can not run it as a Junit test, I am using TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use,
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ApplicationServiceImplTest {
#Mock
ApplicationDao dao;
#InjectMocks
ApplicationMutatorServiceImpl applicationMutatorServiceImpl;
#BeforeClass
public void setUp(){
MockitoAnnotations.initMocks(this);
}
#Test
public void testSave() throws Exception {
Application application = new Application();
applicationMutatorServiceImpl.save(application);
System.out.println (application);
}
}
in my pom.xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
Check if you have TestNG plugin installed.
http://singinginthesunlight.blogspot.in/2016/02/testng-for-dummies.html
Otherwise you can run it through Maven

How to mock a private method using PowerMock with Mockito and TestNG

I am trying to use powermock to mock a private method, but my PowerMock is not recognized in MockitoBusinessOperation MockitoBusinessOperation = PowerMock.createPartialMock(MockitoBusinessOperation.class, "inTestMethod"); . I used maven and the dependencies for mockito and powermock are defined in my pom file
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-mockito-release-full</artifactId>
<version>1.4.9</version>
<scope>test</scope>
</dependency>
I don't know if the error is related to powermock with TestNG or I am doing some mistake in my code.
#PrepareForTest(MockitoBusinessOperation.class)
#Test(enabled = true)
public void testReCalculatePrepaids() throws Exception {
MockitoBusinessOperation MockitoBusinessOperation = PowerMock.createPartialMock(MockitoBusinessOperation.class, "inTestMethod");
PowerMock.expectPrivate(MockitoBusinessOperation, "inTestMethod", Id).andReturn("working fine");
when(MockitoBusinessService.creditReport(this.Id)).thenReturn(new String("Decline by only Me"));
String report = MockitoBusinessService.creditReport(this.Id);
String mainReport = MockitoBusinessOperation.creditAproved(this.Id);
}
someone has an idea or any clue lead to the solution
According to the documentation your maven file should have the following definitions:
<properties>
<powermock.version>1.5</powermock.version>
</properties>
<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
please try this way
#Test
public void commandEndHandlerTest() throws Exception
{
Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
retryClientDetail_privateMethod.setAccessible(true);
retryClientDetail_privateMethod.invoke(yourclass.class, null);
}

Categories