SpringUser
SpringUser

Reputation: 1439

junit test : java.lang.ClassCastException

I am trying to implement junit testing with spring data jpa application. On controller level I am trying to implement unit testing. But I am getting Test failure class cast exception error.

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 test class

@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 failure

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)

I am new to junit testing. Can any one tell me what I am doing wrong in test?

Upvotes: 1

Views: 3272

Answers (1)

Fabian Brandes
Fabian Brandes

Reputation: 23

You are trying to cast a Department to Set<Department> at this line:

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

This cannot work. Instead you should create an empty set and then add the department, i.e. like this:

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

Upvotes: 1

Related Questions