I have the following:
Controller class:
@Controller
@RequestMapping("/")
public class MainController {
@Inject
@Named("dbDaoService")
IDaoService dbDaoService;
@RequestMapping(method = RequestMethod.GET)
public String init(ModelMap model) {
List<Tags> tags = dbDaoService.getAllTags();
model.addAttribute("tags", tags);
return "create";
}
}
Service class:
@Service("dbDaoService")
public class DBDaoService implements IDaoService {
@PersistenceContext(unitName = "MyEntityManager")
private EntityManager entityManager;
@Override
@Transactional
public List<Tags> getAllTags() {
if(tags == null) {
TypedQuery<Tags> query = entityManager.createNamedQuery("Tags.findAll", Tags.class);
tags = query.getResultList();
}
return tags;
}
}
Test class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfig.class})
@WebAppConfiguration
public class MainControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
@Test
public void init() throws Exception {
Tags tag1 = new Tags("first");
Tags tag2 = new Tags("second");
DBDaoService mock = org.mockito.Mockito.mock(DBDaoService.class);
when(mock.getAllTags()).thenReturn(Arrays.asList(tag1, tag2));
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("create"))
.andExpect(forwardedUrl("/WEB-INF/views/create.jsp"))
.andExpect(model().attribute("tags", hasItem(
allOf(
hasProperty("name", is("first"))
)
)))
.andExpect(model().attribute("tags", hasItem(
allOf(
hasProperty("name", is("second"))
)
)));
}
}
When I run MainControllerTest
, it fails, because it gets "Tag" entities from DBDaoService
(it means, from database), but I expect it will use mock service.
What's wrong?