Java, Software Development, Spring

Spring MVC – How To Test For View Name

This post shows how to test for a view name in a Spring MVC application. Given a URI, the application returns a specific view name, and we want to test that. Any use-case for this? Well, we could think of a few, but more often than not, we want to make sure that a URI returns the same view name.


Not many projects use Spring MVC nowadays. If some still do, this may come in handy.

  • Spring Boot 2.1.1.RELEASE
  • JDK 8
  • IntelliJ IDEA

The codes in this post also work with the latest Spring Boot version and JDK 9 and above.

Spring MVC Controller That Returns A View Name

Okay, let’s start by creating a project in IntelliJ IDEA by including Spring Web and Spring MVC dependencies. Then, we make a class with @Controller annotation. Next, we create a public method that maps for an HTTP GET request on / URI. The URI returns the “index” view name. This view name refers to an index.html in our project. Consider the following codes.

Our View In Our Spring MVC Project

So, we have a view name, and it refers to an HTML that has the following content. It does not contain much and only displays a “Hello World” on a white page. There are not even JavaScript codes or placeholders.

Test For The View Name

Next, we create a unit test. It uses MockMvc. In line 27, we access the “/” URI, and we are expecting an HTTP OK and the “index” view name.

The solution may be no longer relevant nowadays because most new applications use REST controllers that work with JSON data. However, we can use the same principle for testing REST API and not expecting the response as a view name for an HTML file.

And that’s how we can test for view name in a Spring MVC application.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like