deivarayan AZHAGAPPAN deivarayan AZHAGAPPAN - 3 months ago 19
reST (reStructuredText) Question

Mock rest service (with spring) in junit

I am writing a junit test case for testing the rest calls.

I tried to mock the ticket service, it works fine but when i mock it in the REST service call. it does not mock.

I am using springboot, mongodb with REST.

Any suggestions to solve this problem ?

@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)));
}


}

Answer

The problem is that the TicketRepository used in your TicketService is not the one mocked by mockito.

The one in your test class is instanciated by Mockito itself, whereas the one in your TicketService is instanciated by Spring.

You could make it work by changing your init method:

@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.
}

This way, your TicketService instance will use the mocked ticketRepository.

Comments