Testing using a Mockito in Spring boot app of a method that takes the Model as a parameter

24 views Asked by At

I need to write a test testing the getData(Model model) @Service method via Mockito.

@RestController
@RequestMapping("")
public class RestCtrl {

   @Autowired
   private TestService testService;

   @GetMapping
   public ModelAndView getData(Model model) {
       return testService.getData(model)
   }
}

@Service
public class TestService {

   @Autowired
   private TestServiceRepository testServiceRepository;
 
   public ModelAndView getData(Model model) {
      model.addAttribute("data", testServiceRepository.findAll());
      return new ModelAndView("index");
   }

}


public interface TestServiceRepository extends JpaRepository<TestDTO, Long> {
}

Is it possible write test on a @Service method that returns ModelAndView ?

@SpringBootTest
@ExtendWith(MockitoExtension.class)
class TestServiceClass {
   @InjectMocks
   private TestService testService;

   @Mock
   private TestServiceRepository testServiceRepository;
}
1

There are 1 answers

1
mvmn On

Yes, it's possible.

You can use Mockito to mock an instance of ModelAndView via simple call to Mockito.mock(ModelAndView.class);