junit

2016-08-17 30 views
2

模拟休息服务(带弹簧)我正在编写一个测试其余调用的junit测试用例。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))); 
    } 

}

回答

1

的问题是,在你的票务使用的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. 
} 

这样,你的票务情况下将使用嘲笑ticketRepository。

+0

非常感谢你指出问题:)它的工作:) – Dev