春季启动中的测试服务

时间:2018-12-11 19:17:02

标签: spring junit mocking

当我尝试测试服务时,出现错误:

  

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:HashSet   findAll()无法返回findAll()应该返回List

public class HotelServiceImplTest {
    HotelServiceImpl hotelService;

    @Mock
    HotelRepository hotelRepository;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        hotelService = new HotelServiceImpl(hotelRepository);
    }

    @Test
    public void getHotels() {

        Hotel hotel = new Hotel();
        HashSet<Hotel> hotelData = new HashSet<>();
        hotelData.add(hotel);

        when(hotelService.getHotels()).thenReturn(hotelData);

        Set<Hotel> hotelSet = hotelService.getHotels();

        assertEquals(1,hotelSet.size());

    }
}


@Override
public Set<Hotel> getHotels() {
    Set<Hotel> hotelSet = new HashSet<>();
    hotelRepository.findAll().iterator().forEachRemaining(hotel -> hotelSet.add(hotel));
    return hotelSet;
}

我正在使用JpaRepository。

1 个答案:

答案 0 :(得分:0)

让我尝试更正您的测试,我认为您应该以这种方式实现它:

@RunWith(MockitoJUnitRunner.class)
public class HotelServiceImplTest {

    @InjectMocks
    HotelServiceImpl serviceUnderTest;

    @Mock
    HotelRepository hotelRepository;


    @Test
    public void getHotels() {

        Hotel hotel = new Hotel();
        HashSet<Hotel> hotelData = new HashSet<>();
        hotelData.add(hotel);

        when(hotelRepository.getHotels()).thenReturn(hotelData);

        Set<Hotel> hotelSet = serviceUnderTest.getHotels();

        assertEquals(1,hotelSet.size());

    }
}


@Override
public Set<Hotel> getHotels() {
    Set<Hotel> hotelSet = new HashSet<>();
    hotelRepository.findAll().iterator().forEachRemaining(hotel -> hotelSet.add(hotel));
    return hotelSet;
}