Junit throwing initialization error. Method 'com' not found - java

All the tests are passing . What should I add for this error to disappear? I am assuming some annotation need to be added. It says Method 'com' not found. I am not able to debug . I dont know what is it talking about.
Code:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class test {
#Autowired
private JdbcTemplate jdbcTemplate;
#Autowired
private JdbcImpl jdbcImpl;
#Autowired
private MConfiguration config;
#Autowired
private MUtilities util;
#Test
public void testRetervices() throws Exception {
List<Tervice> marketServices = jdbcImpl.retrieveTervices("em", "Coitis");
assertEquals(marketServices.size(), 4);
}
Thanks for your time.

This got fixed when I changed the package from
import org.junit.jupiter.api.Test; to
import org.junit.Test;
Thanks!

Related

Spring - Autowired is null - Test - UnsatisfiedDependencyException: Error creating bean with name

I'm trying to test my application, I've been trying to solve it for 3 days and I looked for stackoverflow and I still couldn't solve it.
My problem is that Autowired is always null, and even though I import everything suggested as
#RunWith( SpringRunner.class )
#SpringBootTest
public class ESGControllerTest {
#Autowired
private ESGController esgController ;
#Test
public void deveRetornarSucesso_QuandoBuscarLatLong(){
System.out.println(this.esgController);
}
}
or
#RunWith( SpringJUnit4ClassRunner.class )
#ContextConfiguration
public class ESGControllerTest {
#Autowired
private ESGController esgController ;
#Test
public void deveRetornarSucesso_QuandoBuscarLatLong(){
System.out.println(this.esgController);
}
}
is always null and gives this error
EDIT:
ESGController
package br.com.kmm.esgeniusapi.controller;
import br.com.kmm.esgeniusapi.dto.CargaDTO;
import br.com.kmm.esgeniusapi.dto.CargaFilter;
import br.com.kmm.esgeniusapi.entity.AreaEmbargada;
import br.com.kmm.esgeniusapi.entity.Carga;
import br.com.kmm.esgeniusapi.entity.ConfiguracaoCarga;
import br.com.kmm.esgeniusapi.exception.CargaException;
import br.com.kmm.esgeniusapi.inteface.HereReverseGeocode;
import br.com.kmm.esgeniusapi.inteface.HereSearch;
import br.com.kmm.esgeniusapi.service.CargaService;
import br.com.kmm.esgeniusapi.service.ConfiguracaoCargaService;
import br.com.kmm.esgeniusapi.service.IbamaService;
import br.com.kmm.esgeniusapi.service.ReverseGeocodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
#Slf4j
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping("/api/")
#RolesAllowed("VIEW")
#Component
public class ESGController {
#Autowired
ReverseGeocodeService reverseGeocodeService;
#Autowired
IbamaService ibamaService;
#Autowired
CargaService cargaService;
#Autowired
ConfiguracaoCargaService configuracaoCargaService;
#GetMapping(path = "reverse-geocode")
public HereReverseGeocode getRoute(#RequestParam final String location) {
Double lat = Double.parseDouble(location.split(",")[0]);
Double lon = Double.parseDouble(location.split(",")[1]);
return this.reverseGeocodeService.getReverseGeocoding(lat, lon);
}
#GetMapping(path = "search")
public List<HereSearch> search(#RequestParam(name = "q") final String query) {
return this.reverseGeocodeService.search(query);
}
....{
//MORE FUNCTIONS
}
}
I edited and put the ESGController as code for more information.
Is ESGController decorated with #Controller or equivalent so that a bean of that class actually exist in the context?
Is the test class in the same package hierarchy as the rest of the application?
#SpringBootTest by default starts searching in the current package of
the test class and then searches upwards through the package
structure, looking for a class annotated with #SpringBootConfiguration
from which it then reads the configuration to create an application
context.

java.lang.IllegalStateException: Configuration error

Found that IllegalStateException is used to indicate that "a method has been invoked at an illegal or inappropriate time." Now, while doing JUnit testing I found this error. Any help?
N.B: I am beginner in Java Spring Boot Framework. So, solution can be simple one.
found multiple declarations of #BootstrapWith for test class [com.jrp.pma.controller.HttpRequestTest]: [#org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.context.SpringBootTestContextBootstrapper), #org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper)]
package com.jrp.pma.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertEquals;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//#DataJpaTest
public class HttpRequestTest {
#LocalServerPort
private int port;
#Autowired
private TestRestTemplate restTemplate;
#Test
public void homePageReturnsVersionNumberCorrectly_thenSuccess(){
String renderHtml = this.restTemplate.getForObject("http://localhost:" + port + "/", String.class);
assertEquals(renderHtml.contains("3.3.3"), false);
}
}

MockMvc Not working when Controller is in different package (JUnit5)

package com.azry.ptm.api;
import com.azry.ptm.api.model.account.AccountDTO;
import com.azry.ptm.domain.account.Account;
import com.azry.ptm.server.services.AccountService;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.anyLong;
#AutoConfigureMockMvc
#SpringBootTest
public class AccountControllerImplTest {
#Autowired
private MockMvc mockMvc;
#MockBean
public AccountService accountService;
#Test
public void test() throws Exception {
final long entityNo = 10;
Account expectedAccount = Account.builder()
.entityNo(entityNo)
.build();
Mockito.when(accountService.getAccountById(anyLong())).thenReturn(Optional.of(expectedAccount));
MockHttpServletResponse response = mockMvc.perform(ControllerTestHelper.makeGetRequest("account/", String.valueOf(entityNo)))
.andReturn()
.getResponse();
AccountDTO responseAccount = ControllerTestHelper.toObject(response.getContentAsString(), AccountDTO.class);
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertNotNull(responseAccount);
}
}
Here is my mockMvc test. it works only when the controller is in the same module es test, otherwise, when I split the project it returns a 404 error code as no endpoint was found.
has anybody experience using mockMvc in a multi-module spring-boot app?
solved using #WebMvcTest annotation
#WebMvcTest(AccountControllerImpl.class)

Spring Cloud Contract not executing #Before

I am writing tests using Spring Cloud Contract.
In my configuration I am using for test an in memory DB that is created and destroyed at each test run.
In order to test successfully I need to put some data in the DB but it seems like the classic #Before annotation used in jUnit does not work (the code in it is never executed).
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.context.WebApplicationContext;
#ExtendWith(SpringExtension.class)
#SpringBootTest
public class BaseTestClass {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseTestClass.class);
#Autowired
EntityRepository entityRepository;
#Autowired
private WebApplicationContext context;
#Before
public void init() {
// This code never runs
LOGGER.info("Init started");
MyEntity entity1 = new MyEntity();
entityRepository.save(entity1);
}
#BeforeEach
public void setup() {
RestAssuredMockMvc.webAppContextSetup(context);
}
}
What am I missing?
#Before belongs to JUnit4 and earlier while #BeforeEach belongs to JUnit5 as a replacement and clarification of #Before. If you are running with JUnit5, perhaps put all your initialization logic in #BeforeEach (or if it's a one-time init, in #BeforeAll)
I've found a solution that works.
I was adding the #TestInstance decorator incorrectly, here's my working solution:
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.context.WebApplicationContext;
#ExtendWith(SpringExtension.class)
#SpringBootTest
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class BaseTestClass {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseTestClass.class);
#Autowired
EntityRepository entityRepository;
#Autowired
private WebApplicationContext context;
#BeforeAll
public void init() {
LOGGER.info("Init started");
MyEntity entity1 = new MyEntity();
entityRepository.save(entity1);
}
#BeforeEach
public void setup() {
RestAssuredMockMvc.webAppContextSetup(context);
}
}

Cannot resolve .andExpect() method even after implementing Stackoverflow answer

I am aware a question with the exact same title exists but the answer doesn't help me any further.
I am using WebMvcTest to test my controller class. However when it comes to comparing the result using .andExpect, my IDEA (intellij) can't resolve it.
The question with the same title as this one's solution is included in my imports and is unused. I also looked at the spring docs and used the 2 implements needed.
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
Below you will find my entire class and in this case all my imports.
package be.pxl.backend.restapi;
import be.pxl.backend.restapi.controller.UserController;
import be.pxl.backend.restapi.domain.User;
import be.pxl.backend.restapi.manager.UserManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.*;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
//stackoverflow try == unused
import org.springframework.test.web.servlet.ResultActions;
#RunWith(SpringRunner.class)
#WebMvcTest(UserController.class)
public class UserControllerIntegrationTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserManager userManager;
#Test
public void givenUser_WhenGetUser_ThenReturnUser() throws Exception{
User bjorn = new User();
bjorn.setUsername("Bjorn");
bjorn.setPassword("Wachtwoord");
bjorn.setEmail("test#email.be");
given(userManager.getUserById(1L)).willReturn(bjorn);
mockMvc.perform(get("/user/1")
.contentType(MediaType.APPLICATION_JSON)
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].username", is(bjorn.getUsername()))));
}
}
First of all, according to the Checkstyle, you should avoid star imports.
Secondly, you have misplaced two closing parentheses, one in contentType() and the other one in the last call of andExpect(). Below is a working code.
imports:
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import be.pxl.backend.restapi.controller.UserController;
import be.pxl.backend.restapi.domain.User;
import be.pxl.backend.restapi.manager.UserManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
Note the imports are ordered as per Google Java Style.
mock test:
mockMvc.perform(get("/user/1")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].username", is(bjorn.getUsername())));

Categories