I have a Rest API Created with Spring Framework 3.2.4. I am trying to write test cases in the WebApplicationContext. I see from the server log that the xml configuration files are loaded but it fails while executing the TestContextManager.
ROR org.springframework.test.context.TestContextManager- Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#4c980278] to prepare test instance
Here is my Test Class:
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class })
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = {"file:WebContent/WEB-INF/applicationContext.xml","file:WebContent/WEB-INF/spring-security.xml","file:WebContent/WEB-INF/spring-servlet.xml"})
public class AppControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setUp() {
//Mockito.reset();//awesome_service
mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
#Test
public void testGetSignupForm() throws Exception {
this.mockMvc.perform(get("/apps"))
.andExpect(status().isOk());
}
}
Here is my Controller
#Controller
#RequestMapping(value = "/apps")
public class AppController
{
#Resource(name = "appAPIService")
private AppAPIService appAPIService;
#Resource(name = "applicationVersionService")
private ApplicationVersionService applicationVersionService;
#Resource(name = "applicationService")
private ApplicationService applicationService;
#Autowired
Validator validator;
private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class);
#InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Model.class, "model", new PropertyEditorSupport() {
#Override
public void setAsText(String text) {
BasicDBObject obj = (BasicDBObject)JSON.parse(text);
Model model = new Model();
model.setPrice(obj.getInt(ApplicationFields.MODEL_PRICE,0));
model.setTrial(obj.getInt(ApplicationFields.MODEL_TRIAL,0));
model.setType(obj.getString(ApplicationFields.MODEL_TYPE));
setValue(model);
}
});
}
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> find(HttpServletRequest request, #RequestParam(value="query", required=false) String queryString, #RequestParam(value="sort", required=false) String sortString, #RequestParam(value="pageNumber", required=false) Integer pageNumber, #RequestParam(value="limit", required=false) Integer limit, #RequestParam(value="userId", required=false) String hostUserId)
{
ObjectId marketplaceId = null;
try
{
marketplaceId = AuthenticationUtils.getUserId();
BasicDBObject query;
try
{
query = FormatUtils.toJsonObject(queryString);
}
catch(Exception e)
{
return ResponseUtils.badRequest("query", "Invalid query: " + queryString);
}
BasicDBObject sort;
try
{
sort = FormatUtils.toJsonObject(sortString);
}
catch(Exception e)
{
return ResponseUtils.badRequest("sort", "Invalid sort: " + sortString);
}
return appAPIService.find(marketplaceId, query, sort, pageNumber, limit, hostUserId);
}
catch (Exception e)
{
String message = "Unable to find apps";
ToStringBuilder builder = new ToStringBuilder(message);
LoggingUtils.addToBuilder(builder, request);
builder.append("marketplaceId", AuthenticationUtils.getUserId());
LOGGER.error(builder.toString(), e);
return ResponseUtils.internalError();
}
}
....
}
Related
I have a job that looks like this:
#Named
public class MyCamelRouteBuilder extends RouteBuilder {
private static final String JOB_NAME = "abc";
private static final String JOB_METHOD_NAME = "xyz";
private final MyJob myJob;
#Inject
public MyCamelRouteBuilder(MyJob myJob) {
super();
this.myJob = myJob;
}
#Override
public void configure() {
fromF("direct:%s", JOB_NAME)
.routeId(JOB_NAME)
.bean(myJob, JOB_METHOD_NAME)
.end();
fromF("master:some_name_1/some_name_2:scheduler:%s?delay=%s", JOB_NAME, 1234)
.routeId("JobTimer")
.toF("direct:%s", JOB_NAME)
.end();
}
}
A very simplified version of the job class:
#Named
public class MyJob {
private MyJob() {}
}
public void xyz() {
}
}
This does work and it does gets triggered as expected.
The problem starts here:
Now, I also want to create a REST controller that will be able to trigger the exact same job. Something like this:
#Named
#RestController
#RequestMapping
#Validated
public class MyController {
private static final String JOB_NAME = "abc";
private final ProducerTemplate producerTemplate;
#Inject
public MyController(
ProducerTemplate producerTemplate
) {
this.producerTemplate = producerTemplate;
}
#PostMapping(path = "/my_endpoint")
public String run() throws Exception {
producerTemplate.requestBody("direct:" + JOB_NAME);
return "ok";
}
}
But once it reaches this line, the job is not triggered and the request call keeps hanging.
producerTemplate.requestBody("direct:" + JOB_NAME);
Any ideas?
The fix for my problem:
#Named
#RestController
#RequestMapping
#Validated
public class MyController {
private static final String JOB_NAME = "abc";
#Produce("direct:" + JOB_NAME)
private final ProducerTemplate producerTemplate;
private final CamelContext context;
#Inject
public MyController(
ProducerTemplate producerTemplate, CamelContext context
) {
this.producerTemplate = producerTemplate;
this.context = context;
}
#PostMapping(path = "/my_endpoint")
public String run() throws Exception {
Exchange exchange = new DefaultExchange(context);
producerTemplate.send(exchange);
return "ok";
}
}
I have a mapping to patch data:
#Data
#NoArgsConstructor
public class CertificateUpdateDTO {
#InjectString
private String name;
#InjectString
private String description;
#Min(value = 0, message = "Price cannot be negative")
private double price;
#Min(value = 1, message = "Duration cannot be less than one day")
private int duration;
}
#ApiOperation("Update certificate by id")
#ApiResponses({
#ApiResponse(code = 200, message = "If updated successfully or certificate doesn't exist"),
#ApiResponse(code = 400, message = "If JSON object in request body is invalid"),
#ApiResponse(code = 404, message = "Certificate with given id doesn't exist")
})
#PatchMapping(value = "/{id}", consumes = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity update(#PathVariable int id, #Valid #DefaultDto CertificateUpdateDTO certificateUpdateDTO){
if(certificateService.updateCertificate(id, certificateUpdateDTO)){
return ResponseEntity.ok().build();
}
return ResponseEntity.notFound().build();
}
#DefaultDto and #InjectString are my annotations, they just do same as #RequestBody and inject default value to string fields annotated by #InjectString, it works fine.
I need to check if request to this mapping with id 1 returns 404, and it works from curl:
curl -X PATCH -H "Content-Type: application/json" -d '{"duration": "10", "price": "10"}' localhost:8080/v1/certificate/1
Response code of curl is 404.
But when i try to run test it returns 400:
#ExtendWith(SpringExtension.class)
#ContextConfiguration(classes = ControllerTestConfiguration.class, loader = AnnotationConfigContextLoader.class)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CertificateControllerTest {
#Autowired
private CertificateService certificateService;
#Autowired
private CertificateController certificateController;
private ObjectMapper objectMapper = new ObjectMapper();
private MockMvc mockMvc;
#BeforeAll
public void init(){
mockMvc = MockMvcBuilders.standaloneSetup(certificateController).build();
}
#AfterEach
public void postEach(){
reset(certificateService);
}
...
#Test
#SneakyThrows
public void updateFailTest(){
CertificateUpdateDTO certificateUpdateDTO = new CertificateUpdateDTO();
certificateUpdateDTO.setName("c1");
certificateUpdateDTO.setDescription("desk");
certificateUpdateDTO.setDuration(10);
certificateUpdateDTO.setPrice(10);
when(certificateService.updateCertificate(1, certificateUpdateDTO)).thenReturn(false);
mockMvc.perform(patch("/v1/certificate/1")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(certificateUpdateDTO))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is(404));
verify(certificateService, times(1)).updateCertificate(1, certificateUpdateDTO);
}
}
Configuration for current test class is:
#Configuration
public class ControllerTestConfiguration {
...
#Bean
public CertificateService certificateService(){
return mock(CertificateService.class);
}
#Bean
public CertificateController certificateController(){
return new CertificateController(certificateService());
}
#Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
Error message says that duration is invalid: duration = 0
UPD:
I tried to remove #Valid and saw that my annotations don't work in testing enviroment, that how i'm processing them:
public class DefaultValueHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
#Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(DefaultDto.class) != null;
}
#Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest servletRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
BufferedReader reader = servletRequest.getReader();
String body = reader.lines().collect(Collectors.joining());
Class<?> clazz = methodParameter.getParameterType();
Object dto = new ObjectMapper().readValue(body, clazz);
for(Field field : clazz.getDeclaredFields()){
InjectString annotation = field.getAnnotation(InjectString.class);
if(annotation != null){
field.setAccessible(true);
if(ReflectionUtils.getField(field, dto) == null) {
ReflectionUtils.setField(field, dto, annotation.value());
}
}
}
return dto;
}
}
And that how i register MethodResolver:
public class AppConfig implements WebMvcConfigurer {
private final Environment env;
#Autowired
public AppConfig(Environment env) {
this.env = env;
}
...
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new DefaultValueHandlerMethodArgumentResolver());
}
...
}
After a little bit of researching and my leed fiend's help i found solution :)
To add custom ArgumentResolver you should register it in your MockMvcBuilder.
Change this:
mockMvc = MockMvcBuilders.standaloneSetup(certificateController).build();
To this:
mockMvc = MockMvcBuilders.standaloneSetup(certificateController).setCustomArgumentResolvers(new DefaultValueHandlerMethodArgumentResolver()).build();
This is the actual code
RateNegotiationController.java
#GetMapping(value = "/rate-negotiation/{uniqueId}", produces = {APPLICATION_JSON_VALUE})
public ResponseEntity<RateNegotiation> rateNegotiationByUniqueId(#PathVariable(name = "uniqueId") final String uniqueId) {
final RateNegotiation rateNegotiation =
rateNegotiationService.retrieveRateNegotiationsByUniqueId(uniqueId);
final Optional<String> courierID = validationUtils.getCourierIDFromToken();
if (courierID.isPresent()) {
if (!courierID.get().equals(rateNegotiation.getCourierId())) {
return ResponseEntity.notFound().build();
}
log.info("RateNegotiationController, rateNegotiationByUniqueId {} ", rateNegotiation);
return ResponseEntity.ok(rateNegotiation);
}
throw new CourierIdNotFoundException(COURIER_ID_NOT_FOUND);
}
ValidationUtils.java
public Optional<String> getCourierIDFromToken() {
if (appConfigBean.isSecurityEnabled()) {
return Optional.of(requestPayloadValidator.getCourierIDFromToken());
}
return Optional.empty();
}
I am writing the testcase for this one ..
#MockBean
private ValidationUtils validationUtils;
#MockBean
private AppConfigBean appConfigBean;
#MockBean
private RequestPayloadValidator requestPayloadValidator;
#Test
public void shouldRetrieveRateNegotiationDetailsByUniqueId(){
when(validationUtils.getCourierIDFromToken()).thenReturn(Optional.of("123456"));
when(appConfigBean.isSecurityEnabled()).thenReturn(true);
when(requestPayloadValidator.getCourierIDFromToken()).thenReturn("123456");
rateNegotiationServiceWireMockRule.stubFor(WireMock.get(urlEqualTo(RETRIEVE_RATE_NEGOTIATION_BY_UNIQUE_ID_PATH))
.willReturn(aResponse()
.withHeader(CONTENT_TYPE, APPLICATION_JSON_CHARSET)
.withBodyFile("RateNegotiationByUniqueId.json")
.withStatus(200)
)
);
given()
.port(port)
.when()
.header(CONTENT_TYPE, APPLICATION_JSON_CHARSET)
.get(RETRIEVE_RATE_NEGOTIATION_BY_UNIQUE_ID_URL)
.then()
.assertThat()
.statusCode(200);
}
but still it is not wokring and , showing error,CourierIdNotFoundException: Courier ID not found
I have mock the method validationUtils.getCourierIDFromToken() but still it is not wokring
can anyone please help ?
DemoAppController.java
package com.application.packagename.controller;
#RestController
#Api(value="demoappcontroller", description="Application configuration")
#RequestMapping("app")
#ApiIgnore
public class DemoAppController {
#Autowired
SomeService service;
#ApiOperation(value = "demo app config", response = DemoReponse.class)
#RequestMapping(value="/v1/getDemoAppInfo", produces = "application/json", method= RequestMethod.GET)
public ResponseEntity getDesc(#Valid DemoAppRequest demoAppRequest) {
DemoReponse response = service.getDemoAppInfo(demoAppRequest.getVarNameOne(),
demoAppRequest.getEnvType());
return new ResponseEntity(response, HttpStatus.OK);
}
}
DemoAppRequest.java
package com.application.packagename.model;
#Data
#Component("demoapprequestVo")
#ApiModel("demoapprequestVo")
public class DemoAppRequest {
#ApiModelProperty(example = "value1")
public String varNameOne;
#ApiModelProperty(example = "value2")
public String varNameTwo;
}
DemoAppControllerTest.java
public class DemoAppControllerTest extends TestServiceApiIntegerationTest {
private MultiValueMap<String, String> requestParams;
private URI url;
#BeforeEach
void init() {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("varNameOne", "value 1");
params.add("varNameTwo", "value 2");
requestParams = params;
url = URI.create("/app/v1/getDemoAppInfo/");
}
#Test
public void testGetDesc() throws Exception {
mockMvc.perform(get(url)
.params(requestParams))
.andExpect(status().isOk());
}
}
TestServiceApiIntegerationTest.java
#SpringBootTest
#AutoConfigureMockMvc
public class TestServiceApiIntegerationTest {
#Autowired
protected MockMvc mockMvc;
}
This is just a template for unit testing , you can follow and implement it in your project.
I have a service class, that executes user's request:
public class UnitServiceImpl extends HttpRequestServiceImpl implements UnitService {
private final UnitRepository unitRepository;
public UnitServiceImpl(UnitRepository unitRepository) {
this.unitRepository = unitRepository;
}
#Override
public Unit addUnit(String unitName) {
final Unit unit = new Unit();
unit.setUnitName(unitName);
return unitRepository.save(unit);
}
#Override
public Unit getUnit(int id) {
final Unit unit = unitRepository.findById(id);
if (unit == null) {
throw new EntityNotFoundException("Unit is not found");
}
return unit;
}
#Override
public Unit updateUnit(int id, String unitName) {
final Unit unit = getUnit(id);
unit.setUnitName(unitName);
return unitRepository.save(unit);
}
#Override
public Iterable<Unit> getAllUnits() {
return unitRepository.findAll();
}
}
Controller, that's use Service:
#RestController
public class UnitController {
private final UnitService managementService;
public UnitController(UnitService managementService) {
this.managementService = managementService;
}
#GetMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Iterable<Unit>> getAllUnits() {
final Iterable<Unit> allUnits = managementService.getAllUnits();
return new ResponseEntity<>(allUnits, HttpStatus.OK);
}
#PostMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> addUnit(HttpServletRequest request) throws FieldsIsAbsentException {
final String unitName = managementService.getParameter(request, "unit_name");
final Unit unit = managementService.addUnit(unitName);
return new ResponseEntity<>(unit, HttpStatus.CREATED);
}
#GetMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> getUnitById(#PathVariable("id") int id) {
final Unit unit = managementService.getUnit(id);
return new ResponseEntity<>(unit, HttpStatus.OK);
}
#PutMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> updateUnit(HttpServletRequest request, #PathVariable("id") int id) {
final String unitName = managementService.getParameter(request, "unit_name");
return new ResponseEntity<>(managementService.updateUnit(id, unitName), HttpStatus.ACCEPTED);
}
}
I created unit tests. They are mockito methods isn't working. All test methods doing request to database. Test class:
#SpringBootTest
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationTestConfig.class)
#WebAppConfiguration
#AutoConfigureMockMvc
class UnitControllerTest {
#Autowired
private MockMvc mockMvc;
#Mock
UnitService unitService;
#Autowired
private UnitController unitController;
private final List<Unit> units = new ArrayList<>();
#BeforeEach
public void initUnits() {
this.mockMvc = MockMvcBuilders.standaloneSetup(unitController)
.setControllerAdvice(new ExceptionHandlingController()).build();
Unit unit = new Unit();
unit.setUnitName("someUnit 1");
unit.setId(1);
units.add(unit);
unit = new Unit();
unit.setId(2);
unit.setUnitName("Some unit 2");
units.add(unit);
}
#Test
void testGetAllUnits() throws Exception {
when(this.unitService.getAllUnits()).thenReturn(units);
mockMvc.perform(get("/unit"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
#Test
void testUnitNotFound() throws Exception {
int id = -1;
given(this.unitService.getUnit(id)).willThrow(EntityNotFoundException.class);
mockMvc.perform(get("/unit/" + id))
.andDo(print())
.andExpect(status().isNotFound())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
#Test
void testUnitFound() throws Exception {
int id = 5;
Unit unitWithName = new Unit();
unitWithName.setId(id);
unitWithName.setUnitName("NameUnit");
given(unitService.getUnit(id)).willReturn(unitWithName);
mockMvc.perform(get("/unit/" + id).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(id))
.andExpect(jsonPath("$.unitName").value(unitWithName.getUnitName()));
}
#Test
void testAddUnit() throws Exception {
Unit unit = new Unit();
unit.setId(1);
unit.setUnitName("TestUnit");
given(unitService.addUnit("TestUnit")).willReturn(unit);
mockMvc.perform(post("/unit").param("unit_name", "TestUnit"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.unitName").value(unit.getUnitName()))
.andExpect(jsonPath("$.id").value(1));
}
}
This code is trying to read or write to database. I've tried so many variants.
I've been trying to write tests for a few days.=( What is the error?
I've changed my test class onto next code and it works now:
#WebMvcTest(UnitController.class)
class UnitControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
UnitService unitService;
private final List<Unit> units = new ArrayList<>();
#BeforeEach
public void initUnits() {
Unit unit = new Unit();
unit.setUnitName("someUnit 1");
unit.setId(1);
units.add(unit);
unit = new Unit();
unit.setId(2);
unit.setUnitName("Some unit 2");
units.add(unit);
}
///test methods
There are are many questions of same type, but none works for me.
I have Spring MVC hibernate application.
Here are my two model classes
Config.java
public class Config implements java.io.Serializable {
private Integer configId;
private String configName;
private Set<ConfigFields> ConfigFieldses = new HashSet<ConfigFields>(0);
//getters and setters
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="configuration")
public Set<ConfigFields> getConfigFieldses() {
return this.ConfigFieldses;
}
public void setConfigFieldses(Set<ConfigFields> ConfigFieldses) {
this.ConfigFieldses = ConfigFieldses;
}
}
ConfigFields.java
public class ConfigFields implements java.io.Serializable {
private Integer configFieldId;
private Confign config;
private String configFieldName;
//getteres and setters
#XmlTransient
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="ConfigId")
public Config getConfig() {
return this.config;
}
public void setConfig(Config configu) {
this.config = config;
}
}
Here is GenericHibernateDao.java
#Repository
#Transactional
public class GenericHibernateDao<T extends Serializable>
implements GenericDao<T>{
#Resource
protected SessionFactory sessionFactory;
#Override
public void insert(T transientInstance) {
sessionFactory.getCurrentSession().persist(transientInstance);
}
#Override
public void update(T instance) {
sessionFactory.getCurrentSession().saveOrUpdate(instance);
}
#Override
public void delete(T persistentInstance) {
sessionFactory.getCurrentSession().delete(persistentInstance);
}
#SuppressWarnings("unchecked")
#Override
public T merge(Serializable detachedInstance) {
return (T) sessionFactory.getCurrentSession().merge(detachedInstance);
}
#SuppressWarnings("unchecked")
#Override
public T findById(Class<?> clazz, Serializable id) {
T t= (T) sessionFactory.openSession().get(clazz, id);
return t;
}
#SuppressWarnings("unchecked")
public List<T> findByNamedQuery(Class<T> clazz, String queryName, Map<String, Object> queryParams) {
Query namedQuery = sessionFactory.getCurrentSession().getNamedQuery(queryName);
for (String s : queryParams.keySet()) {
namedQuery.setParameter(s, queryParams.get(s));
}
return namedQuery.list();
}
}
In my controller I have this method
#RequestMapping(value = "/deleteConfig/{configId}", method = RequestMethod.POST)
#ResponseBody
#Transactional
public String deleteConfiguration(#PathVariable Integer configId, HttpServletResponse response) throws IOException {
try {
Config config=configService.findById(configId);
logger.info("Deleting configuration...");
configService.delete(config);
} catch(Exception e) {
logger.debug(e.getMessage());
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
return "success";
}
My test case
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration("classpath:webapptest")
#ContextConfiguration(locations = {"classpath:test-applicationcontext.xml"})
public class ConfigurationsControllerTest {
private MockMvc springMvc;
#Autowired
WebApplicationContext wContext;
#Before
public void init() throws Exception {
springMvc = MockMvcBuilders.webAppContextSetup(wContext).build();
}
#Test
public void deleteConfiguration() throws Exception {
ResultActions resultActions=springMvc.perform(MockMvcRequestBuilders.post("/deleteConfig/117").accept(MediaType.APPLICATION_JSON));
resultActions.andDo(MockMvcResultHandlers.print());
resultActions.andExpect(MockMvcResultMatchers.status().isOk());
}
}
When I run the testcase in console, logger showing
Illegal attempt to associate a collection with two open sessions
And JUnit test case stacktrace is
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is bitronix.tm.internal.BitronixRollbackException: transaction was marked as rollback only and has been rolled back
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:932)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
In Config class, I have Set which is set to CASCADE ALL. SO I am able to insert set of configfields while inserting config too. But now I want to delete by passing config object. So it should delete 1 row from config table and few rows from configfields table based on configId.
What is wrong here? And how to solve without affecting application(I mean insert)