【问题标题】:Spring Controller test弹簧控制器测试
【发布时间】:2017-02-08 08:25:52
【问题描述】:

我有以下几点:

控制器类:

@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 unit-testing junit mockito


【解决方案1】:

当前测试设置加载弹簧配置并使用WebApplicationContext 来处理由于MockMvcBuilders.webAppContextSetup(context).build(); 而产生的请求。因此,模拟 bean 被忽略,因为它们没有被指示参与。

要将它们交织在一起,应该将配置更新为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"))
                )
            )));
    }
}

【讨论】:

  • 好的,太好了!但是我仍然有两个问题。首先: andExpect(forwardedUrl("/WEB-INF/views/create.jsp")) 导致错误:java.lang.AssertionError: Forwarded URL Expected :/WEB-INF/views/create.jsp 实际:create
  • 第二个问题:andExpect(model().attribute("tags", hasItem(allOf( hasProperty("name", is("first"))))))) 效果很好,但是第二个 andExpect(model().attribute("tags", hasItem(allOf(hasProperty("name", is("second")))))) 抛出错误NoSuchMethodError: org.hamcrest.Matcher.describeMismatch(Ljava/lang/Object;Lorg/hamcrest/Description;)V
  • 关于第一个问题 - 请参阅更新。在独立配置的情况下需要显式视图解析器
  • 关于第二个问题(不确定为什么一个语句有效而第二个语句失败) - 您可以尝试herehere 描述的步骤
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 2016-03-28
  • 2014-02-09
  • 2013-01-11
  • 2013-06-17
  • 2020-05-26
  • 1970-01-01
相关资源
最近更新 更多