I had my first test working some days ago, and today I went to verify and complete them, and now it simply gives me this error. My OrderControllerTest.java
package com.proj.my.controller;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
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 java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.Order;
import com.proj.my.model.ShoppingCart;
import com.proj.my.model.User;
import com.proj.my.service.CloudProductService;
import com.proj.my.service.OrderService;
import com.proj.my.service.UserService;
@WebMvcTest(OrderController.class)
public class OrderControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private OrderService orderService;
@MockBean
private CloudProductService cloudProductService;
@MockBean
private UserService userService;
CloudProduct cloudProductOne;
ShoppingCart shoppingCartOne;
Order orderOne;
User user;
List<ShoppingCart> shoppingCartList= new ArrayList<>();
List<Order> orderList= new ArrayList<>();
@BeforeEach
void setUp() {
cloudProductOne = new CloudProduct(1, "Amazon",
(float) 232);
shoppingCartOne = new ShoppingCart(1, 2);
shoppingCartList.add(shoppingCartOne);
user = new User("Mariaaaa");
orderOne = new Order(user, LocalDate.now(), shoppingCartList);
orderList.add(orderOne);
}
@AfterEach
void tearDown() {
}
@Test
void testGetAllOrderDetails() throws Exception {
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minusDays(1);
when(orderService.getAllOrderDetail(today)).thenReturn(orderList);
this.mockMvc.perform(get("/api/getOrder"))
.andDo(print()).andExpect(status().isOk());
}
@Test
void testPlaceOrder() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
String requestJson=ow.writeValueAsString(orderOne);
when(orderService.saveOrder(orderOne)).thenReturn(orderOne);
this.mockMvc.perform(post("/api/placeOrder")
.contentType(MediaType.APPLICATION_JSON)
.content(requestJson))
.andDo(print()).andExpect(status().isOk());
}
}
My OrderController.java
package com.proj.my.controller;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.dto.OrderDTO;
import com.proj.my.dto.ResponseOrderDTO;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.Order;
import com.proj.my.model.ShoppingCart;
import com.proj.my.model.User;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
import com.proj.my.service.OrderService;
import com.proj.my.service.UserService;
@RestController
@RequestMapping("/api")
public class OrderController {
private OrderService orderService;
private CloudProductService cloudProductService;
private UserService userService;
@Autowired
private CloudProductRepository cloudProductRepository;
public OrderController(OrderService orderService, CloudProductService cloudProductService, UserService userService) {
this.orderService = orderService;
this.cloudProductService = cloudProductService;
this.userService = userService;
}
@GetMapping(value = "/getOrder/{orderId}")
public ResponseEntity<Order> getOrderDetails(@PathVariable int orderId) {
Order order = orderService.getOrderDetail(orderId);
return ResponseEntity.ok(order);
}
@GetMapping(value = "/getOrders/{dataaa}")
public List<Order> getAllOrderDetails(@PathVariable LocalDate dataaa) {
return orderService.getAllOrderDetail(dataaa);
}
@PostMapping("/placeOrder")
public ResponseEntity<?> placeOrder(@RequestBody OrderDTO orderDTO) {
ResponseOrderDTO responseOrderDTO = new ResponseOrderDTO();
List<ShoppingCart> shoppingCartList = orderDTO.getCartItems();
ShoppingCart shoppingCart;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()){
float amount = orderService.getCartAmount(orderDTO.getCartItems());
if(amount > 0){
User user = new User(orderDTO.getuserEmail());
Integer userIdFromDb = userService.isUserPresent(user);
if (userIdFromDb != null) {
user.setUserId(userIdFromDb);
}else{
user = userService.createUser(user);
}
LocalDate createdAt = LocalDate.now();
Order order = new Order(user, createdAt, orderDTO.getCartItems());
order = orderService.saveOrder(order);
responseOrderDTO.setAmount(amount);
responseOrderDTO.setDate(com.proj.my.util.DateUtil.getCurrentDateTime());
responseOrderDTO.setOrderId(order.getId());
return ResponseEntity.ok(responseOrderDTO);
}
else{
return new ResponseEntity<>("Can't create an order without products.", HttpStatus.OK);
}
}
else{
return new ResponseEntity<>("No Product with such name found.", HttpStatus.OK);
}
}
return null;
}}
and my error
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@7f5614f9 testClass = com.proj.my.controller.OrderControllerTest, locations = [], classes = [com.proj.my.MyApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper=true"], contextCustomizers = [[ImportsContextCustomizer@480cbe2e key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration, org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration, org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration, org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration, org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration, org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration, org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration, org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration, org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration, org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration, org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration, org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration, org.springframework.boot.test.autoconfigure.web.reactive.WebTestClientAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6f44a157, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@17d88132, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@a564f78a, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@172b013, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@9da1, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@74bba8e8, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@476a54ad, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4f5991f6, org.springframework.boot.test.context.SpringBootTestAnnotation@a378d012], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:141)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:110)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:94)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:61)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:249)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(Unknown Source)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Unknown Source)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Unknown Source)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(Unknown Source)
at java.base/java.util.Optional.orElseGet(Unknown Source)
at java.base/java.util.ArrayList.forEach(Unknown Source)
at java.base/java.util.ArrayList.forEach(Unknown Source)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderController': Unsatisfied dependency expressed through field 'cloudProductRepository': No qualifying bean of type 'com.proj.my.repository.CloudProductRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:712)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:692)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:127)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:481)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1397)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:598)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:59)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:47)
at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1386)
at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:543)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:183)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 73 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.proj.my.repository.CloudProductRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1812)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1371)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1325)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:709)
... 98 more
Besides that, when everything about this error was okay, I was unable to test the second function there, because "the order was null", and I don't get why !! So, how can I solve this error ?
Your error says No qualifying bean of type 'com.proj.my.repository.CloudProductRepository' available
. You should have your repository annotated with @Repository
or extending a JpaRepository
or so.