gpt4 book ai didi

mongodb - junit中的模拟休息服务(带 Spring )

转载 作者:可可西里 更新时间:2023-11-01 10:42:01 25 4
gpt4 key购买 nike

我正在编写一个 junit 测试用例来测试其余调用。

我尝试模拟票务服务,它工作正常,但是当我在 REST 服务调用中模拟它时。它不会 mock 。

我正在使用带有 REST 的 springboot、mongodb。

有什么解决这个问题的建议吗?

@RestController
@RequestMapping("/ticket")
public class TicketRestController
{
@Autowired
public TicketService ticketService;

@RequestMapping (path = "/all", method = {RequestMethod.GET})
public List<Ticket> getAllTicket()
{
return ticketService.getAll();
}
}


public interface TicketService
{

public List<Ticket> getAll();
}


@Service
public class TicketServiceImpl implements TicketService {

@Autowired
TicketRepository ticketRepository;

public List<Ticket> getAll() {
return ticketRepository.findAll();
}
}



public interface TicketRepository extends MongoRepository<Ticket, String> {

public List<Ticket> findAll();

}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/mongo-repository-context.xml")
@WebAppConfiguration
public class TicketControllerTest extends AbstractTicketTest {

public static final String PATH = "/ticket";

public static final String ALL = PATH + "/all";

public static final String ID = PATH + "/id";

public static final String STATE = PATH + "/state";

public static final String PAYMENT_TYPE = PATH + "/paymentType";

public static final String TABLE_NUMBER = PATH + "/tableNumber";

@Autowired
private WebApplicationContext ctx;

private MockMvc mockMvc;

@Autowired
@InjectMocks
private TicketService ticketService;

@Mock
private TicketRepository ticketRepository;

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
ticketRepository.deleteAll();
}

@Test
public void getAllTickets() throws Exception {
Mockito.when(ticketRepository.findAll()).thenReturn(TicketMockProvider.createTickets());

this.mockMvc.perform(get(ALL))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)))
.andExpect(jsonPath("$[0].ticketItems", hasSize(2)));
}

最佳答案

问题是您的 TicketService 中使用的 TicketRepository 不是 mockito 模拟的那个。

您的测试类中的一个由 Mockito 本身实例化,而您的 TicketService 中的一个由 Spring 实例化。

您可以通过更改 init 方法使其工作:

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
ticketRepository.deleteAll();
// new code starts here
ticketService.setTicketRepository(ticketRepository); // this method needs to be created.
}

这样,您的 TicketService 实例将使用模拟的 ticketRepository。

关于mongodb - junit中的模拟休息服务(带 Spring ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38997883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com