用Junit测试控制器?

时间:2018-11-23 15:25:43

标签: java unit-testing spring-boot junit mockito

在使用Spring Boot应用程序设置单元测试时遇到了一些麻烦。我的主要问题是控制器中需要的“模型”对象,但是我找不到在测试中重新创建它的方法,而使用我的函数是必需的。

这是我要测试的功能

@Controller
public class AjoutAbscenceControler {

  @Autowired
  private AbsenceRepository absenceRepository;

  @RequestMapping(value = { "/addAbsence" }, method = RequestMethod.GET)
  public String showAddAbsencePage(Model model) {

    Absence absence = new Absence();
    model.addAttribute("Absence", absence);

    return "addAbsence";
  }

  @RequestMapping(value = { "/addingAbsence" }, method = RequestMethod.POST)
  public String saveAbsence(Model model, @ModelAttribute("absence") Absence absence) {

    if (absence.getName() != null && absence.getName().length() > 0) {
      absenceRepository.save(absence);
    }
    return "redirect:/userList";
  }

}

我确实尝试过类似的事情

@RunWith(MockitoJUnitRunner.class)
public class AjoutAbscenceControlerTest {

  @Mock
  VacationRepository vacationRepository;
  @Mock
  CategoryRepository categoryRepository;
  @InjectMocks
  AjoutAbscenceControler controler;
  public MockMvc mockMvc;
  @Before
  public  void  setUp() throws Exception{
    mockMvc = MockMvcBuilders.standaloneSetup(controler).build();
  }
  @Test
  public void showAddAbsencePagetest() {
  AjoutAbscenceControler ajoutAbscenceControler =new AjoutAbscenceControler();

    assertEquals("addAbsence",ajoutAbscenceControler.showAddAbsencePage(controler));
  }
}

但是我找不到创建springfarmwork.ui.Model

的任何方法

1 个答案:

答案 0 :(得分:2)

如果要测试控制器的逻辑,则可能不应该创建Model对象,而应对其进行模拟并验证与之的交互作用:

@Mock
private Model model;

@Test
public void showAddAbsencePagetest() {
    // Should probably be initialized in a @Before method,
    // Initialized here for clarity only
    AjoutAbscenceControler ajoutAbscenceControler = new AjoutAbscenceControler();

    assertEquals("addAbsence", ajoutAbscenceControler.showAddAbsencePage(model));

    Mockito.verify(model).addAttribute(eq("Absence"), any(Absence.class));
}