Just made a controller in Spring Boot and I want to unit test it.
The code of the controller and its method is:
@Controller
@RequestMapping("/projects/{pid}/clusters")
public class ClusterController {
@Autowired
private ClusterService clusterService;
@Autowired
private ProjectService projectService;
@RequestMapping(method = RequestMethod.GET)
public String getAllClusters(@PathVariable("pid") Integer projectId, Model model){
Project project = this.projectService.getProjectById(projectId);
Set<Cluster> clusters = project.getClusters();
model.addAttribute("projectID", projectId);
model.addAttribute("clusters", clusters);
return "clusters";
}
This method simply returns a view (HTML) when a user gets to a specific URL.
Code of my test:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class clusterControllerTest {
@LocalServerPort
private int port;
private URL base;
@Autowired
private TestRestTemplate testRestTemplate;
@Before
public void setUp() throws Exception{
}
@Test
public void getCluster() throws Exception{
this.base = new URL("http://localhost:" + port + "/projects/1/clusters");
ResponseEntity<String> response = testRestTemplate.getForEntity(base.toString(), String.class);
assertThat(response.getBody(), equalTo("clusters"));
}
}
I'm already testing my repository and service layer in other tests. I only want to get the right return when navigating to a specific URL (which calls a specific method in de Controller).
In my examply when someone goes to "http://localhost:" + port + "/projects/1/clusters" The Controller should return "clusters".
When I execute this code I get the error that says my assertThat went wrong. Because "clusters" is compared to the whole html page.
How can I easily just test the return string of my controller? I don't have much experience with testing. Much thanks in advance!
Aucun commentaire:
Enregistrer un commentaire