Mockito没有退还期望值

时间:2019-03-05 21:09:06

标签: spring-boot mockito

我为一个函数创建了一个单元测试,但是当要从flatRepository中找到实体时,它会返回:

  

me.flatkeepr.exception.ResourceNotFoundException:找不到Flat 1

     在

  me.flatkeepr.service.TaskService.lambda $ create $ 2(TaskService.java:54)     在java.base / java.util.Optional.orElseThrow(Optional.java:408)在   me.flatkeepr.service.TaskService.create(TaskService.java:54)

这应该如何工作?

到目前为止我尝试过的是: -添加了@Mock注释 -将MockitoAnnotations.initMocks(this)放入init函数中 -将Optional.of放在返回值中

@RunWith(MockitoJUnitRunner.class)
public class TaskServiceTest {

    @Mock
    private final TaskRepository taskRepository = Mockito.mock(TaskRepository.class);

    @Mock
    private final FlatRepository flatRepository = Mockito.mock(FlatRepository.class);

    @Mock
    private final UserRepository userRepository = Mockito.mock(UserRepository.class);

    @InjectMocks
    private TaskService taskService;



    @Test
    public void createTaskWithNoDeadLine() {
        TaskDTO fresh = new TaskDTO();
        fresh.setName("Clean up");
        fresh.setScore(10);
        fresh.setDescription("Short summary");

        Flat flat = new Flat();
        flat.setName("Flat");

        Task task = TaskMapper.INSTANCE.convertToEntity(fresh);
        task.setId(1L);

        when(taskRepository.existsByNameAndFlatId(fresh.getName(), 1L)).thenReturn(false);
        when(flatRepository.findById(1L)).thenReturn(Optional.of(flat));
        when(taskRepository.save(task)).thenReturn(task);

        TaskDTO actual = taskService.create(1L, fresh);


        assertEquals("Clean up", actual.getName());
        assertEquals(10, actual.getScore().intValue());
        assertEquals("Short summary", actual.getDescription());
    }
}

服务层中的功能:

public create(Long flatId, TaskDTO fresh) {
return flatRepository.findById(flatId).map(flat -> {
                Task task = createEntity(fresh);
                task.setId(null);
                task.setFlat(flat);
                return createDTO(taskRepository.save(task));
            }).orElseThrow(() -> new ResourceNotFoundException("Flat " + flatId + " not found"));
}

1 个答案:

答案 0 :(得分:0)

我想我解决了我的问题:

代替此:

return createDTO(taskRepository.save(task));

我应该这样写:

taskRepository.save(task);
return createDTO(task);

现在它通过了测试