junit test:java.lang.ClassCastException

时间:2018-04-07 05:05:29

标签: unit-testing junit spring-data-jpa

我正在尝试使用spring data jpa应用程序实现junit测试。在控制器级别,我正在尝试实现单元测试。但是我收到Test failure class cast异常错误。

DepartmentController.java

@RestController
@RequestMapping("/api.spacestudy.com/SpaceStudy/Control/SearchFilter")
public class DepartmentController {

    @Autowired
    DepartmentService depService;

    @CrossOrigin(origins = "*")
    @GetMapping("/loadDepartments")
    public ResponseEntity<Set<Department>> findDepName() {

        Set<Department> depname = depService.findDepName();
        return ResponseEntity.ok(depname);
    }
}

Junit测试课

@RunWith(SpringRunner.class)
@WebMvcTest(DepartmentController.class)
public class SpaceStudyControlSearchFilterApplicationTests {

    @Autowired
    DepartmentController depController;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    DepartmentService depService;

    @SuppressWarnings("unchecked")
    Set<Department> mockDepartment = (Set<Department>) new Department(21629, "170330", "Administrative Computer");


    @Test
    public void findDepNameTest() throws Exception {

        Mockito.when(depService.findDepName()).thenReturn( mockDepartment);
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                "/api.spacestudy.com/SpaceStudy/Control/SearchFilter/loadDepartments").accept(
                MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        System.out.println(result.getResponse());
        String expected = "{nDeptId: 21629}";

        JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);

    }
}

Junit失败

java.lang.ClassCastException: com.spacestudy.model.Department cannot be cast to java.util.Set
    at com.spacestudy.SpaceStudyControlSearchFilterApplicationTests.<init>(SpaceStudyControlSearchFilterApplicationTests.java:39)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)

我是junit测试的新手。谁能告诉我在测试中我做错了什么?

1 个答案:

答案 0 :(得分:0)

您正在尝试在此行将Department投射到Set<Department>

Set<Department> mockDepartment = (Set<Department>) new Department(21629, "170330", "Administrative Computer"); 

这不起作用。相反,您应该创建一个空集,然后添加部门,即:

Set<Department> mockDepartment = new HashSet<Department>() {{
  add(new Department(21629, "170330", "Administrative Computer"));
}};