我在Java的Spring Boot控制器中创建了一个函数,该函数使我可以根据参数获取数据的总和,效果很好。但是,我很难理解用Junit和Mockito测试此功能的最佳方法是什么?到目前为止,我已经创建了一个测试函数,该函数返回一个特定数组字段的值。 如何在.thenReturn()中返回一个根据给定serviceID求和的值?
对其他有用帖子的任何帮助或建议,将不胜感激,因为我无法找到任何相关内容,或者我正在寻找错误的地方。
谢谢
下面,我展示了我的控制器中的功能
@GetMapping("/orders/test/{serviceId}")
public Double findRevenueByService(@PathVariable Long serviceId){
log.info("Start of findRevenueByService method {}", serviceId);
return repository.findPaymentRevenue(serviceId);
}
在存储库中查询
@Query("select SUM(o.amount) from ORDERS o where o.serviceId = :serviceId")
Double findPaymentRevenue(@Param("serviceId") Long serviceId);
TestController
package PPBackend.controller;
import PPBackend.domain.Order;
import PPBackend.repository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.when;
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.jsonPath;
@Slf4j
public class OrdersControllerTest {
@InjectMocks
private OrdersController controller;
private MockMvc mockMvc;
@Mock
private OrderRepository repository;
private List<Order> orders = new ArrayList<>();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
orders.add(new Order(1L,1L,10.00, 50.00,LocalDateTime.now(),LocalDateTime.now()));
orders.add(new Order(2L,2L,20.00, 50.00,LocalDateTime.now(),LocalDateTime.now()));
orders.add(new Order(3L,1L,30.00, 50.00,LocalDateTime.now(),LocalDateTime.now()));
orders.add(new Order(4L,3L,40.00, 50.00,LocalDateTime.now(),LocalDateTime.now()));
orders.add(new Order(5L,1L,50.00, 50.00,LocalDateTime.now(),LocalDateTime.now()));
}
@After
public void tearDown() {
orders = new ArrayList<>();
}
@Test
public void findRevenueByService() throws Exception {
final Long serviceId = 1L;
when(repository.findPaymentRevenue(serviceId)).thenReturn(orders.get(0).getAmount());
this.mockMvc.perform(get("/api/test/" + serviceId)).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isNotEmpty())
.andExpect(jsonPath("$").value(10.00))
.andExpect(status().isOk());
}
}
域对象
private Long id;
private Long serviceId;
private Double amount;
private Double credit;
private LocalDateTime created;
private LocalDateTime lastEdited;
答案 0 :(得分:1)
通过使用解决 Java8: sum values from specific field of the objects in a list作为参考,需要稍作修改