【发布时间】:2016-12-24 04:26:51
【问题描述】:
我正在编写一个 junit 测试用例来测试其余的调用。
我试图模拟票务服务,它工作正常,但是当我在 REST 服务调用中模拟它时。它不模拟。
我正在使用 springboot、mongodb 和 REST。
有解决这个问题的建议吗?
@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)));
}
}
【问题讨论】:
标签: mongodb rest spring-boot mockito junit4