Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Mocking with Mockito

Matchers.instanceOf method does not compile

I am following the video precisely, and the Matchers.instanceOf method used in detail_ShouldErrorOnNotFound() is not recognized by my Intellij IDE or the java 8 compiler. I may have a problem with one of my imports. My code is below: import com.teamtreehouse.domain.Favorite; import com.teamtreehouse.service.FavoriteNotFoundException; import com.teamtreehouse.service.FavoriteService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.internal.matchers.InstanceOf; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.util.Arrays; import java.util.List;

import static com.teamtreehouse.domain.Favorite.FavoriteBuilder; import static org.mockito.Mockito.; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.;

<code omitted> @Test public void detail_ShouldErrorOnNotFound() throws Exception { // Arrange the mock behavior when(service.findById(1L)).thenThrow(FavoriteNotFoundException.class);

    // Act (perform the MVC request) and Assert results
    mockMvc.perform(get("/favorites/1"))
            .andExpect(view().name("error"))
              .andExpect(model().attribute("ex", Matchers.instanceOf(FavoriteNotFoundException.class));  // instanceOf not recognized
    verify(service).findById(1L);

Found a solution slightly different from the code shown in the video:

import org.hamcrest.CoreMatchers;

mockMvc.perform(get("/favorites/1")) .andExpect(view().name("error")) .andExpect(model().attribute("ex", CoreMatchers.instanceOf(FavoriteNotFoundException.class)));

1 Answer

Fahad Mutair
Fahad Mutair
10,359 Points

hi Iver Band , you missed to import org.hamcrest.Matchers; for Matchers.instanceOf(FavoriteNotFoundException.class)

Not import org.mockito.internal.matchers.InstanceOf;