弹簧控制器测试



>我有以下内容:

控制器类:

@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("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;
    }
}

测试类:

@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"))
                    )
            )));
    }
}

当我运行 MainControllerTest 时,它失败了,因为它从DBDaoService(这意味着从数据库中(获取"标记"实体,但我希望它会使用模拟服务。

怎么了?

当前的测试设置加载 spring 配置并使用WebApplicationContext来处理由于MockMvcBuilders.webAppContextSetup(context).build();的请求。因此,被嘲笑的豆子被忽略了,因为它们没有被指示参与。

要交织它们,应将配置更新为MockMvcBuilders.standaloneSetup(controller).build()

示例测试用例应如下所示(请注意用于MainController和配置更新的附加模拟MockMvcBuilders.standaloneSetup以及通过 MockitoAnnotations.initMocks 使用 Mockito 注释的说明(

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfig.class})
@WebAppConfiguration
public class MainControllerTest  {
    private MockMvc mockMvc;
    @InjectMocks
    private MainController controller;
    @Mock
    private DBDaoService daoService;
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        mockMvc = MockMvcBuilders.standaloneSetup(controller)
                             .setViewResolvers(viewResolver)
                             .build();
        Tags tag1 = new Tags("first");
        Tags tag2 = new Tags("second");
        when(daoService.getAllTags()).thenReturn(Arrays.asList(tag1, tag2));
    }
    @Test
    public void init() throws Exception {
        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"))
                )
            )));
    }
}

相关内容

  • 没有找到相关文章

最新更新