2016-08-17 5 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

問題は、あなたの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を使用します。

+0

問題を指摘していただきありがとうございます:)それは動作します:) – Dev

関連する問題