title: Mock device for controller test
body: <p>I am trying to write a unit test for a controller that does different things depending on the device type.  </p>
  
  <p>The first controller method and its test works fine, the method paramater <em>model</em> has a value and I can validate the value in the test.</p>
  
  <p>The second controller method which expects a device works when called from a brwoser, but <strong>not</strong> in a unit test. When the test method <code>doSomething2Test()</code> is called I get a </p>
  
  <pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.mobile.device.Device]: Specified class is an interface
  </code></pre>
  
  <p>My question: Why is the parameter <em>model</em> instantiated correctly but <em>device</em> is not? Is there a way to set the device in the MockMvc request or can I mock the device somehow?</p>
  
  <p>Controller:</p>
  
  <pre><code>@Controller
  @RequestMapping("home")
  public class MyController {
  
      @RequestMapping("/test1")
      public String doSomething1(Model model) {
          String value = "foo";
          model.addAttribute("attribute1", value);        
          return "newUrl";
      }
  
      @RequestMapping("/test2")
      public String doSomething2(Model model, Device device) {
          if (device.isNormal()) {
            // do stuff
          }
          return "newUrl";
      }
  }
  </code></pre>
  
  <p>Test: </p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest(classes = Application.class, webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
  @WithMockUser(username="admin", authorities = {"ALL"})
  public class MyControllerTest {
  
      private MockMvc mockMvc;
  
      @InjectMocks
      private MyController controllerUnderTest;   
  
      @Before
      public void setUp() {
          MockitoAnnotations.initMocks(this);
          InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
          viewResolver.setPrefix("/WEB-INF/classes/templates");
          viewResolver.setSuffix(".html");
          this.mockMvc =
                  MockMvcBuilders.standaloneSetup(this.controllerUnderTest)
                          .setViewResolvers(viewResolver)
                          .build();
      }
  
      @Test
      public void doSomething1Test() throws Exception {
          this.mockMvc.perform(get("/home/test1"))
          .andExpect(status().isOk())
          .andExpect(model().attribute("attribute1", contains("foo")));   
      }
  
      @Test
      public void doSomething2Test() throws Exception {
          this.mockMvc.perform(get("/home/test2"))
          .andExpect(status().isOk()));   
      }
  }
  </code></pre>