spring unit testing controller not resolving WebAppContext - spring

I have read online tutorials on unit testing spring MVC, I have copied from tutorials but WebAppContext.class never resolves as a type. What should this resolve too?
package com.doyleisgod.springmavenexample.controllers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.Arrays;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {TestContext.class, WebAppContext.class})
#WebAppConfiguration
public class HomeControllerTest {
private MockMvc mockMvc;
#Test
public void indexTest() {
mockMvc.perform(get("/index.htm", 1L))
.andExpect(status().isOk())
.andExpect(view().name("index"))
.andExpect(forwardedUrl("/WEB-INF/views/index.jsp"));
}
}
Eclipse shows WebAppContext cannot be resolved to a type
How do i fix this?

Are you referring to
org.springframework.web.context.WebApplicationContext; or
org.springframework.test.context.web.WebAppConfiguration;
You need spring-test dependencies to resolve these.

Related

spring boot unit test can not resolve get

why inteli J can not resolve get in my unit test ?
package com.stev.pillecons.pilleCons;
import com.stev.pillecons.pilleCons.controllers.LePilleController;
import com.stev.pillecons.pilleCons.services.PilleService;
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.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
#RunWith(SpringRunner.class)
#WebMvcTest(LePilleController.class)
public class UnitTestPille {
#Autowired
private MockMvc mockMvc;
#MockBean
PilleService pilleService;
#Test
public void getAllPille() throws Exception {
mockMvc.perform(get("/api/pille"))
.andExpect(status().isOk())
.andExpect(content())
}
}
all get(),status(), and content() are Red
You are missing the static imports:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class

In my microservice Spring Boot application i added Swagger for my REST api's documentation. Before that my Spring Boot microservice was started fine. But When I add my add my SwaggerConfig the project can't start. I had this error :
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.myproject.MyApplication]; nested exception is java.io.FileNotFoundException: class path resource [springfox/bean/validators/configuration/BeanValidatorPluginsConfiguration.class] cannot be opened because it does not exist
The SwaggerConfig is in common project that add to dependency into my microservice pom.
This my project configuration
SwaggerConfig
package com.project.common.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
#Configuration
#EnableSwagger2
#Import({ BeanValidatorPluginsConfiguration.class })
public class SwaggerConfig {
#Value("${swagger.api.title: no title}")
private String title;
#Value("${swagger.api.package}")
private String apipackage;
#Value("${swagger.api.version:no version}")
private String version;
#Value("${swagger.api.description:no description}")
private String description;
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage(apipackage))
.paths(PathSelectors.any()).build().useDefaultResponseMessages(false)
.apiInfo(new ApiInfoBuilder().title(title).description(description)
.version(version).build())
.globalResponseMessage(RequestMethod.GET,defaultResponse())
.globalResponseMessage(RequestMethod.POST,defaultResponse())
.globalResponseMessage(RequestMethod.PUT,defaultResponse())
.globalResponseMessage(RequestMethod.DELETE,defaultResponse());
}
private static List<ResponseMessage> defaultResponse(){
return
List.of(new ResponseMessageBuilder().code(500).message("Internal server error").build(),
new ResponseMessageBuilder().code(400).message("bad request").build(),
new ResponseMessageBuilder().code(404).message("not found").build());
}
}
Main class
package com.project.company;
import com.project.common.config.SwaggerConfig;
import com.project.company.infrastructure.config.MyApplicationConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import java.util.ArrayList;
import java.util.List;
#SpringBootApplication(exclude={SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
#Import({MyApplicationConfig.class, SwaggerConfig.class})
public class MyCompanyApplication {
public static void main(String[] args) {
SpringApplication.run(MyCompanyApplication.class, args);
}
#Bean
public CommandLineRunner init(){
return (String... args)->{
// do something
};
}
}
I found my error. I forgot this dependency :
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
</dependency>

How to write Spring boot test cases in multiple files for multiple controller respectively

I am using JUnit and Mockito to write test cases for Spring Boot Application. I have multiple controllers(For eg: ContractController and CountryCOntroller). When I write test cases for both of them in a single file , test will pass but if I write ContractController test cases in one file and the other controller test cases in second file , test cases fail.
Can you please let me know how to write in different files?
Contract Controller TEst
package com.example.demo;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
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;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.example.demo.controllers.ContractController;
import com.example.demo.controllers.CountryController;
import com.example.demo.entities.Contract;
import com.example.demo.entities.Country;
import com.example.demo.repositories.ContractRepository;
import com.example.demo.repositories.CountryRepository;
#RunWith(SpringRunner.class)
public class ContractControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private ContractRepository contractRepository;
#SuppressWarnings("unchecked")
#Test
public void testGetContract() throws Exception {
System.out.println("contract testing");
Contract contract = new Contract();
contract.setContractTypeId(1);
contract.setContractType("Calibration");
Mockito.when(this.contractRepository.findAll()).thenReturn((Collections.singletonList(contract)));
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/contractType").accept(MediaType.APPLICATION_JSON_UTF8);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println("result is"+result.getResponse().getContentAsString());
String expected = "[{id:1,contractType:Calibration}]";
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);
}
}
COuntry COntroller Test
package com.example.demo;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
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 org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.example.demo.controllers.CountryController;
import com.example.demo.entities.Contract;
import com.example.demo.entities.Country;
import com.example.demo.repositories.ContractRepository;
import com.example.demo.repositories.CountryRepository;
#RunWith(SpringRunner.class)
#WebMvcTest(value = CountryController.class)
public class CountryControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private CountryRepository countryRepository;
#MockBean
private ContractRepository contractRepository;
#SuppressWarnings("unchecked")
#Test
public void testGetCountries() throws Exception {
System.out.println("mockito testing");
Country country = new Country();
country.setId(1);
country.setCountryName("Afghanistan");
country.setShortName("AF");
Mockito.when(this.countryRepository.findAll()).thenReturn((Collections.singletonList(country)));
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/countries").accept(MediaType.APPLICATION_JSON_UTF8);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println("result is"+result.getResponse().getContentAsString());
String expected = "[{id:1,shortName:AF,countryName:Afghanistan}]";
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);
}

Spring controller tests with mocks

So I'm having some issues coming up with a solution for a test.
This is the method I want to test(I'm new to this). It clears all fields on a web page each time it's loaded.
#RequestMapping("/addaddressform")
public String addAddressForm(HttpSession session)
{
session.removeAttribute("firstname");
session.removeAttribute("surname");
session.removeAttribute("phone");
session.removeAttribute("workno");
session.removeAttribute("homeno");
session.removeAttribute("address");
session.removeAttribute("email");
return "simpleforms/addContact";
}
and here's what i have so far for the test
package ControllerTests;
import java.text.AttributedCharacterIterator.Attribute;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration (classes = {SimpleFormsControllerTest.class})
public class SimpleFormsControllerTest {
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
#Test
public void addAddressForm_ExistingContactDetailsInForm_RemovalFromSession() throws Exception{
MockHttpSession mockSession = new MockHttpSession();
mockSession.putValue("firstname", "test");
mockSession.putValue("surname", "test");
mockSession.putValue("phone", "test");
mockSession.putValue("workno", "test");
mockSession.putValue("homeno", "test");
mockSession.putValue("address", "test");
mockSession.putValue("email", "test");
mockMvc.perform(get("simpleForms/addaddressform").session(mockSession));
}
As this is the first time I've ever had to do this kind of thing I don't have much clue where to go with this.
Then you have to do is only assert the values, e.g.:
assertNull(mockSession.getAttribute("firstname"));
If you want to make sure it is the case, you can do:
assertNotNull(mockSession.getAttribute("firstname"));
before you fire the GET request.

passing objects between Spring MVC Controller and model

I am new to Spring MVC. I have created a controller like this and a model is a POJO. When I build my application, it gives me the error:
Controller:
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.model.dto.BillingContactDto;
/**
* The Class BillingController.
*/
#Controller
public class BillingController extends BillingBaseFormController {
/** The log. */
private static final Logger LOG = LoggerFactory.getLogger(BillingController.class);
//model class
private BillingContactDto billingContactDto;
//this is how I believe I should link both of them
#ModelAttribute("emp")
public BillingContactDto getEmployee(#RequestParam("empdId") Long id) {
// Get employee using empId from DB
return billingContactDto;
}
#RequestMapping(value = "/showEmpDetail", method = RequestMethod.GET)
public String showEmpDetails() {
return "showEmpDetail";
}
error
[ERROR] C:\src\billing\web\src\main\java\com\billing\webapp\controller\company\BillingController.java:[142,12] error: cannot find symbol.
I need some guidance as to where I am going wrong.
Thanks in advance

Resources