Mapping two #GetMapping to same #RestController into Spring Boot - java

I need to mapping two GET methods look like:
GET /tickets - Retrieves a list of tickets
GET /tickets/12 - Retrieves a specific ticket
But when I mapped this, the Spring got confused!
When I hit http://localhost:8080/tickets in the Chrome, the result on server is:
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "tickets"]
When I hit http://localhost:8080/tickets/12 in the Chrome, the result on server is:
QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
My Spring controller is:
package wendelsilverio.api.ticket;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
#RestController("tickets")
public class TicketController {
#Autowired
private TicketRepository repository;
#GetMapping
public List<TicketEntity> getTickets() {
return repository.findAll();
}
#GetMapping("/{id}")
public Optional<TicketEntity> getTicket(#PathVariable("id") Long id) {
return repository.findById(Long.valueOf(id));
}
}
My unit test is:
package wendelsilverio.api.ticket;
import static org.hamcrest.CoreMatchers.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 java.util.Arrays;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
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.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
#SpringBootTest
#AutoConfigureMockMvc
#RunWith(SpringRunner.class)
public class TicketControllerRestfulTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private TicketController mockTicketController;
#Test
public void getTickets() throws Exception {
given(mockTicketController.getTickets())
.willReturn(Arrays.asList(new TicketEntity(1L, "First ticket"), new TicketEntity(2L, "Second ticket")));
mockMvc.perform(get("tickets").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$[0].content", is("First ticket")))
.andExpect(jsonPath("$[1].content", is("Second ticket")));
}
#Test
public void getTicket12() throws Exception {
Optional<TicketEntity> twelveTicket = Optional.of(new TicketEntity(12L, "Twelve ticket"));
given(mockTicketController.getTicket(12L)).willReturn(twelveTicket);
mockMvc.perform(get("tickets/12").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(12L))).andExpect(jsonPath("$.content", is("Twelve ticket")));
}
}
I'm using Java 11 and Spring Boot 2.1.6

Use
#RestController
#RequestMapping("/tickets")
...
#GetMapping
...
#GetMapping("{id}")
In your code
1) #RestController("tickets") means 'create bean named "tickets"'
2) second URL (#GetMapping("/{id}")) tells 'put ID at root' (http://localhost:8080/ID) - so controller cannot convert 'tickets' to long.

Related

Spring Boot REST API app, testing Controller layer with JUNIT

hi i am learning Java and Spring Framework, i don't even consider myself beginner. The other day i found great study material "Spring-Boot Masterclass". I am learning from this source, first part was about making simple REST API CRUD application with custom methods, custom exceptions, by using MySQL database. I've learned a lot from this source, and everything went smooth, i understood everything till now, i am at testing repository, service and controller layers. I managed to create tests for CRUD methods + few custom methods for all 3 layers, and all tests passed with green result in Eclipse, i just stopped at void deleteMinisterstvo() method. Question is in Controller Layer above mentioned method in comment, but i'll share it here too, because i am getting lost:
HOW is this working, when i create database record with id=15, then delete ID=4 from endPoint for ID= 55, and TEST passes? Which one is being deleted then?
Maybe i did not even write method as it should be written, so i would like to ask you, experienced developers on your opinion, idea, maybe explanation. Thanks
*Note1: I started this thread with Hi, i... but it somehow did not save, so i tried to edit and even edit does not give Hi there. Sorry for that.
*Note2: I removed all other methods (commented them out) from Repository, Service and Controller layers for focusing only at deleteMethod. I thought, that this test should not pass, but throw error:
Project
MinisterstvoRepository
package com.Ministerstvo.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.Ministerstvo.Model.Ministerstvo;
#Repository
public interface MinisterstvoRepository extends JpaRepository<Ministerstvo, Long>{
}
MinisterstvoService
package com.Ministerstvo.Service;
import java.util.List;
import com.Ministerstvo.Exceptions.MinisterstvoNotFoundException;
import com.Ministerstvo.Model.Ministerstvo;
public interface MinisterstvoService {
void odstranMinisterstvo(Long id) throws MinisterstvoNotFoundException;
}
MinisterstvoServiceImpl
package com.Ministerstvo.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.Ministerstvo.Controller.MinisterstvoController;
import com.Ministerstvo.Exceptions.MinisterstvoNotFoundException;
import com.Ministerstvo.Model.Ministerstvo;
import com.Ministerstvo.Repository.MinisterstvoRepository;
import lombok.AllArgsConstructor;
import lombok.Data;
#Service
#Data
#AllArgsConstructor
public class MinisterstvoServiceImpl implements MinisterstvoService {
#Autowired
private final MinisterstvoRepository ministerstvoRepository;
private final Logger LOGGER = LoggerFactory.getLogger(MinisterstvoController.class);
#Override
public void odstranMinisterstvo(Long id) throws MinisterstvoNotFoundException {
LOGGER.info("Metoda odstranMinisterstvo() v MinisterstvoServiceImpl");
Optional<Ministerstvo> ministerstvo = ministerstvoRepository.findById(id);
if(!ministerstvo.isPresent()) {
throw new MinisterstvoNotFoundException("Ministerstvo so zadanym ID neexistuje...");
}
ministerstvoRepository.deleteById(id);
}
}
MinisterstvoController
package com.Ministerstvo.Controller;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.Ministerstvo.Exceptions.MinisterstvoNotFoundException;
import com.Ministerstvo.Model.Ministerstvo;
import com.Ministerstvo.Service.MinisterstvoService;
import lombok.AllArgsConstructor;
import lombok.Data;
#RestController
#Data
#AllArgsConstructor
public class MinisterstvoController {
#Autowired
private final MinisterstvoService ministerstvoService;
private final Logger LOGGER = LoggerFactory.getLogger(MinisterstvoController.class);
// API - DELETE
#DeleteMapping("/ministerstva/{id}")
public ResponseEntity<String> odstranMinisterstvo(#PathVariable("id") Long id) throws MinisterstvoNotFoundException {
LOGGER.info("Metoda odstranMinisterstvo() v MinisterstvoController");
ministerstvoService.odstranMinisterstvo(id);
return new ResponseEntity<String>("Uspesne odstranene ministerstvo", HttpStatus.OK);
}
}
MinisterstvoControllerTest
package com.Ministerstvo.Controller;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import com.Ministerstvo.Model.Ministerstvo;
import com.Ministerstvo.Service.MinisterstvoService;
import com.fasterxml.jackson.databind.ObjectMapper;
#WebMvcTest
#ExtendWith(MockitoExtension.class)
class MinisterstvoControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private MinisterstvoService ministerstvoService;
Ministerstvo ministerstvo;
List<Ministerstvo> zoznamMinisterstiev;
#BeforeEach
void setUp() throws Exception {
ministerstvo = Ministerstvo.builder()
.ministerstvoId(6L)
.ministerstvoName("MinisterstvoKultiry")
.ministerstvoEmail("kultura#gmail.com")
.ministerstvoPocetZamestnancov(5)
.build();
}
#AfterEach
void tearDown()
{
ministerstvo = null;
}
// DELETE TEST
// HOW IS THIS WORKING, WHEN I CREATE DB RECORD WITH ID 15, then delete ID 4 from endPoint for ID 55, and TEST passes?
#Test
void deleteMinisterstvo() throws Exception
{
Ministerstvo ministerstvoNadstranenie = Ministerstvo.builder()
.ministerstvoId(15L)
.ministerstvoName("Ministerstvo of Nothing")
.ministerstvoEmail("nothing#gmail.com")
.ministerstvoPocetZamestnancov(789)
.build();
doNothing().when(ministerstvoService).odstranMinisterstvo(4L);
// same result as from doNothing() above //doNothing().when(ministerstvoService).odstranMinisterstvo(ministerstvo.getMinisterstvoId());
// same result as from mockMvc.perform() below
//mockMvc.perform(delete("/ministerstva/55")
mockMvc.perform(delete("/ministerstva/"+ ministerstvoNadstranenie.getMinisterstvoId().toString())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
}
}
If i forgot to provide more details, i will add them based on instructions. I am just curious, if test for delete method is working properly, would be great to know the way, why test passes with different data.
Thanks for reading,
have a nice day

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)

How to Use FakeMongo and Ignore MongoDB socket connection on Controller level Integration testing

I am using spring boot 1.5.x for application. Database is MONGO
Using MongoRepository for crud operations.
Earlier in our project we got dedicated test database instance so we have added mongodb properties of test db in src\test\resources\application.properties.
Now we dont have test db so we want to use embedded/fake db to test our classes Controller/Services/Repository etc..
Options are - embeded mongodb like flapdoodle and fongo
I tried 1 of solution de.flapdoodle.embed.mongo from SO question to use flapdoodle
de.flapdoodle.embed.mongo trying to download zip outside network : unable-to-download-embedded-mongodb-behind-proxy-using-automatic-configuration
I tried fakemongo but its not working for unit and integration testing of controller. Its picking mongo database details of test db using application.properties present in test/resources
pom.xml
<dependency>
<groupId>com.github.fakemongo</groupId>
<artifactId>fongo</artifactId>
<version>${fongo.version}</version>
<!--<scope>test</scope> -->// not working, if removed it says cannot find mongo
</dependency>
<dependency>
<groupId>com.lordofthejars</groupId>
<artifactId>nosqlunit-mongodb</artifactId>
<version>0.7.6</version>
<scope>test</scope>
</dependency>
FakeMongo Configuration
package com.myapp.config;
import com.github.fakemongo.Fongo;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
#Configuration
#EnableMongoRepositories
public class FakeMongo extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "mockDB";
}
#Bean
public MongoClient mongo() {
Fongo fongo = new Fongo("mockDB");
return fongo.getMongo();
}
}
TestFakeMongo It works. Test executed properly - Reference http://springboot.gluecoders.com/testing-mongodb-springdata.html
package com.myapp.config;
import com.myapp.domain.entitlement.User;
import com.myapp.repository.UserRepository;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.core.LoadStrategyEnum;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.junit.Assert.assertTrue;
#RunWith(SpringRunner.class)
#Import(value = {FakeMongo.class})
public class TestFakeMongo {
#Autowired
private ApplicationContext applicationContext;
#Rule
public MongoDbRule embeddedMongoDbRule = newMongoDbRule().defaultSpringMongoDb("mockDB");
#MockBean
private UserRepository userRepository;
#Test
#UsingDataSet(loadStrategy = LoadStrategyEnum.DELETE_ALL)
public void getAllUsers_NoUsers() {
List<User> users = userRepository.findAll();
assertTrue("users list should be empty", users.isEmpty());
}
}
UserRepositoryTest - Unit testing for Repository also working using fongo Reference - http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html
package com.myapp.repository;
import com.myapp.config.SpringUnitTest;
import com.myapp.domain.User;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class UserRepositoryTest extends SpringUnitTest {
#Autowired
private UserRepository userRepository;
#Before
public void setup() {
importJSON("user", "user/user.json");
}
#Test
//#UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT, locations = "/json-data/user/user.json") // test/resources/..
public void findUser_should_return_user() {
User user = userRepository.findByXYZId("XX12345");
assertNotNull(user);
}
#Test
public void findUser_should_return_null() {
User user = userRepository.findByXYZId("XX99999");
assertNull(user);
}
#Test
public void deleteUser_should_return_null() {
userRepository.delete("XX12345");
User user = userRepository.findByXYZId("XX12345");
assertNull(user);
}
#Test
public void saveUser_should_return_user() {
User user = new User();
user.setXYZId("XX12345");
user.setAck(true);
List<DateTime> dateTimeList = new ArrayList<>();
dateTimeList.add(DateTime.now(DateTimeZone.UTC));
user.setAckOn(dateTimeList);
User dbUser = userRepository.save(user);
assertEquals(user, dbUser);
}
#Test
public void findAllUser_should_return_users() {
List<User> userList = userRepository.findAll();
assertEquals(1, userList.size());
}
}
Controller level testing not working.. Reference- https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/
UserControllerTest failed java.lang.IllegalStateException: Failed to load ApplicationContext - At this point test mongo db details fetech instead of fongo test\resources\application.properties test server db details are loading
package com.myapp.config;
package com.myapp.controllers;
import com.myapp.config.FakeMongo;
import com.myapp.services.persistance.UserService;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
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.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#ActiveProfiles("it")
#RunWith(SpringRunner.class)
#SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = Application.class
)
#Import(value = {FakeMongo.class})
#AutoConfigureMockMvc
#TestPropertySource(locations = "classpath:application-it.properties")
public class UserControllerTest {
#Rule
public MongoDbRule embeddedMongoDbRule = newMongoDbRule().defaultSpringMongoDb("mockDB");
#Autowired
private MockMvc mockMvc;
#MockBean
private UserService service;
#Before
public void setUp() throws Exception {
}
#Test
public void deleteUser() throws Exception {
Mockito.when(this.service.deleteUser(Mockito.anyString())).thenReturn(true);
this.mockMvc.perform(delete("/User")).andDo(print()).andExpect(status().isOk())
.andExpect((ResultMatcher) content().string(containsString("true")));
}
}
UserControllerTest Not working, failing with error java.lang.IllegalStateException: Failed to load ApplicationContext as its tries to connect to test instance of mongo database using application.properties present in test/resources
Appreciate working example to use fakemongo while running Integration test for Controller level
What changes, I need to do in code level(Controller class or any other class) or application.properties of test\resources ?

Categories