thenreturn()想要可选,但测试失败

发布于 2025-02-02 11:03:13 字数 5581 浏览 3 评论 0原文

我正在尝试进行单元测试,但是我收到错误'无法解决方法(可疑测试);使用java.optional'包裹,但是当我这样做(.thenreturn(可选)时(可疑的(可疑test)),测试失败 - “不能将可选的可疑性施加到class suscect”。这是测试,suspectservice和suspectservice和suspectcontroller(已编辑(已编辑)张贴*)。

@DataJpaTest
public class ControllerTest {
    @Mock
    Model model;
    @Mock
    SuspectService suspectService;
    SuspectController suspectController;

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Before
    public void setUp() throws Exception {
        suspectController = new SuspectController(suspectService);
    }

    @Captor
    ArgumentCaptor<Suspect> argumentCaptor;


    @Test
    public void showById() {
        Integer id = 1;
        Suspect suspectTest = new Suspect();
        suspectTest.setId(Long.valueOf(id));

        when(suspectService.getById(Long.valueOf(id))).thenReturn(Optional.of(suspectTest));

        String viewName = suspectController.showById(id.toString(), model);
        Assert.assertEquals("info", viewName);
        verify(suspectService, times(1)).getById(Long.valueOf(id));

        verify(model, times(1))
                .addAttribute(eq("suspect"), argumentCaptor.capture() );

        Suspect suspectArg = argumentCaptor.getValue();
        Assert.assertEquals(suspectArg.getId(), suspectTest.getId() );

    }
}


@Service
public class SuspectService implements BaseService<Suspect> {
    private final com.unibuc.AWBD_Project_v1.repositories.SuspectRepository suspectRepository;

    @Autowired
    public SuspectService(SuspectRepository SuspectRepository) {
        this.suspectRepository = SuspectRepository;
    }

    @Override
    public Suspect insert(Suspect object) {
        return suspectRepository.save(object);
    }

    @Override
    public Suspect update(Long id, Suspect updatedObject) {
        var foundId =  suspectRepository.findById(id);

        return foundId.map(suspectRepository::save).orElse(null);
    }

    @Override
    public List<Suspect> getAll() {
        return suspectRepository.findAll();
    }

    @Override
    public Optional<Suspect> getById(Long id) {
        return suspectRepository.findById(id);
    }

    @Override
    public void deleteById(Long id)
    {
        try {
            suspectRepository.deleteById(id);
        } catch (SuspectException e) {
            throw  new SuspectException("Suspect not found");
        }
    }

    @Override
    public Page<Suspect> findAll(int page, int size, String sortBy, String sortType){
        Sort sort = sortType.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortBy).ascending() :
                Sort.by(sortBy).descending();
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        return  suspectRepository.findAll(pageable);
    }

}


@RestController
@RequestMapping("/api/suspect")
public class SuspectController implements BaseController<Suspect> {
    private final com.unibuc.AWBD_Project_v1.services.SuspectService SuspectService;

    @Autowired
    public SuspectController(SuspectService SuspectService) {
        this.SuspectService = SuspectService;
    }

    @PostMapping("/suspects/add")
    @Override
    public String NewObject(Model model) {

        model.addAttribute("suspect", new Suspect());
        return "addsuspect";
    }

    @PostMapping("/suspects/update/{id}")
    @Override
    public String update(@PathVariable Long id, @Valid @ModelAttribute("suspect") Suspect suspect, BindingResult bindingResult, Model model) {
        if(bindingResult.hasErrors())
        {
            boolean update = true;
            model.addAttribute("update", update);
            return "addsuspect";
        }
        SuspectService.insert(suspect);
        return "redirect:/suspects";
    }

    @DeleteMapping("/suspects/delete/{id}")
    @Override
    public String deleteById(@PathVariable Long id) {
        try {
            SuspectService.deleteById(id);
        } catch (SuspectException e)
        {
            throw new SuspectException("Suspect with " + id + " does not exist!");
        }
        return "redirect:/suspects";
    }

    @GetMapping("/suspect/{id}")
    public String showById(@PathVariable String id, Model model){
        model.addAttribute("suspect",
                SuspectService.getById(Long.valueOf(id)));
        return "info";
    }


    @RequestMapping("/suspects")
    public String objectsList(@RequestParam(value = "page", required = false) Integer page,
                              @RequestParam(value = "sortBy", required = false) String sortBy,
                              @RequestParam(value = "sortType", required = false) String sortType, Model model) {
        int size = 5;
        if (page == null)
            page = 1;
        if(sortBy==null)
            sortBy ="name";
        if(sortType==null)
            sortType ="asc";
        Page<Suspect> pageSuspect = SuspectService.findAll(page, size, sortBy, sortType);
        List<Suspect> suspects = pageSuspect.getContent();

        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", pageSuspect.getTotalPages());
        model.addAttribute("totalItems", pageSuspect.getTotalElements());

        model.addAttribute("sortBy", sortBy);
        model.addAttribute("sortType", sortType);
        model.addAttribute("reverseSortDir", sortType.equals("asc") ? "desc" : "asc");
        model.addAttribute("suspects", suspects);
        var suspect = new Suspect();
        model.addAttribute("suspect", suspect);
        return "suspects";
    }


}

I'm trying to do an Unit test, but I receive the error 'cannot resolve the method thenReturn(suspectTest) ; wrap using java.Optional', but when I do (.thenReturn(Optional.of(suspectTest)), the test fails - 'Optional cannot be cast to class Suspect'. Here it is the test, the SuspectService and the SuspectController (edited post*). Thank you in advance!

@DataJpaTest
public class ControllerTest {
    @Mock
    Model model;
    @Mock
    SuspectService suspectService;
    SuspectController suspectController;

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Before
    public void setUp() throws Exception {
        suspectController = new SuspectController(suspectService);
    }

    @Captor
    ArgumentCaptor<Suspect> argumentCaptor;


    @Test
    public void showById() {
        Integer id = 1;
        Suspect suspectTest = new Suspect();
        suspectTest.setId(Long.valueOf(id));

        when(suspectService.getById(Long.valueOf(id))).thenReturn(Optional.of(suspectTest));

        String viewName = suspectController.showById(id.toString(), model);
        Assert.assertEquals("info", viewName);
        verify(suspectService, times(1)).getById(Long.valueOf(id));

        verify(model, times(1))
                .addAttribute(eq("suspect"), argumentCaptor.capture() );

        Suspect suspectArg = argumentCaptor.getValue();
        Assert.assertEquals(suspectArg.getId(), suspectTest.getId() );

    }
}


@Service
public class SuspectService implements BaseService<Suspect> {
    private final com.unibuc.AWBD_Project_v1.repositories.SuspectRepository suspectRepository;

    @Autowired
    public SuspectService(SuspectRepository SuspectRepository) {
        this.suspectRepository = SuspectRepository;
    }

    @Override
    public Suspect insert(Suspect object) {
        return suspectRepository.save(object);
    }

    @Override
    public Suspect update(Long id, Suspect updatedObject) {
        var foundId =  suspectRepository.findById(id);

        return foundId.map(suspectRepository::save).orElse(null);
    }

    @Override
    public List<Suspect> getAll() {
        return suspectRepository.findAll();
    }

    @Override
    public Optional<Suspect> getById(Long id) {
        return suspectRepository.findById(id);
    }

    @Override
    public void deleteById(Long id)
    {
        try {
            suspectRepository.deleteById(id);
        } catch (SuspectException e) {
            throw  new SuspectException("Suspect not found");
        }
    }

    @Override
    public Page<Suspect> findAll(int page, int size, String sortBy, String sortType){
        Sort sort = sortType.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortBy).ascending() :
                Sort.by(sortBy).descending();
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        return  suspectRepository.findAll(pageable);
    }

}


@RestController
@RequestMapping("/api/suspect")
public class SuspectController implements BaseController<Suspect> {
    private final com.unibuc.AWBD_Project_v1.services.SuspectService SuspectService;

    @Autowired
    public SuspectController(SuspectService SuspectService) {
        this.SuspectService = SuspectService;
    }

    @PostMapping("/suspects/add")
    @Override
    public String NewObject(Model model) {

        model.addAttribute("suspect", new Suspect());
        return "addsuspect";
    }

    @PostMapping("/suspects/update/{id}")
    @Override
    public String update(@PathVariable Long id, @Valid @ModelAttribute("suspect") Suspect suspect, BindingResult bindingResult, Model model) {
        if(bindingResult.hasErrors())
        {
            boolean update = true;
            model.addAttribute("update", update);
            return "addsuspect";
        }
        SuspectService.insert(suspect);
        return "redirect:/suspects";
    }

    @DeleteMapping("/suspects/delete/{id}")
    @Override
    public String deleteById(@PathVariable Long id) {
        try {
            SuspectService.deleteById(id);
        } catch (SuspectException e)
        {
            throw new SuspectException("Suspect with " + id + " does not exist!");
        }
        return "redirect:/suspects";
    }

    @GetMapping("/suspect/{id}")
    public String showById(@PathVariable String id, Model model){
        model.addAttribute("suspect",
                SuspectService.getById(Long.valueOf(id)));
        return "info";
    }


    @RequestMapping("/suspects")
    public String objectsList(@RequestParam(value = "page", required = false) Integer page,
                              @RequestParam(value = "sortBy", required = false) String sortBy,
                              @RequestParam(value = "sortType", required = false) String sortType, Model model) {
        int size = 5;
        if (page == null)
            page = 1;
        if(sortBy==null)
            sortBy ="name";
        if(sortType==null)
            sortType ="asc";
        Page<Suspect> pageSuspect = SuspectService.findAll(page, size, sortBy, sortType);
        List<Suspect> suspects = pageSuspect.getContent();

        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", pageSuspect.getTotalPages());
        model.addAttribute("totalItems", pageSuspect.getTotalElements());

        model.addAttribute("sortBy", sortBy);
        model.addAttribute("sortType", sortType);
        model.addAttribute("reverseSortDir", sortType.equals("asc") ? "desc" : "asc");
        model.addAttribute("suspects", suspects);
        var suspect = new Suspect();
        model.addAttribute("suspect", suspect);
        return "suspects";
    }


}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文