Spring 弹簧控制器试验

Spring 弹簧控制器试验,spring,unit-testing,junit,mockito,Spring,Unit Testing,Junit,Mockito,我有以下资料: 控制器类: @Controller @RequestMapping("/") public class MainController { @Inject @Named("dbDaoService") IDaoService dbDaoService; @RequestMapping(method = RequestMethod.GET) public String init(ModelMap model) { List&

我有以下资料:

控制器类:

@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())而产生的请求。因此,模拟bean被忽略,因为它们没有被指示参与

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

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


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

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

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


您的服务类似乎缺少一些代码行。您使用覆盖和事务,但没有方法。抱歉,这是一个输入错误。代码是正确的。您的服务类可能缺少一些代码行。您使用覆盖和事务,但没有方法。抱歉,这是一个输入错误。代码是正确的。可能重复的Ok,太好了!但我仍然有两个问题。第一个问题:andExpect(forwardedUrl(“/WEB-INF/views/create.jsp”))导致错误:java.lang.AssertionError:Forwarded URL Expected:/WEB-INF/views/create.jsp实际:created第二个问题:andExpect(model().attribute(“tags”),hasItem(allOf(hasProperty(“name”,is(“First”!)))工作正常,但是第二个andExpect(model().attribute(“tags”),hasItem(allOf(hasProperty(“name”),is(“second”;))))抛出错误NoSuchMethodError:org.hamcrest.Matcher.descripebemmatch(Ljava/lang/Object;Lorg/hamcrest/Description;)解决第一个问题-请参阅更新。在独立配置的情况下需要显式视图解析器关于第二个问题(不确定为什么一条语句有效而第二条语句失败)-您可以尝试所描述的步骤吗?好的,太好了!但我仍然有两个问题。第一个问题:andExpect(forwardedUrl(“/WEB-INF/views/create.jsp”))导致错误:java.lang.AssertionError:Forwarded URL Expected:/WEB-INF/views/create.jsp实际:created第二个问题:andExpect(model().attribute(“tags”),hasItem(allOf(hasProperty(“name”,is(“First”!)))工作正常,但是第二个andExpect(model().attribute(“tags”),hasItem(allOf(hasProperty(“name”),is(“second”;))))抛出错误NoSuchMethodError:org.hamcrest.Matcher.descripebemmatch(Ljava/lang/Object;Lorg/hamcrest/Description;)解决第一个问题-请参阅更新。如果独立配置涉及第二个问题(不确定为什么一条语句有效而第二条语句失败),则需要显式视图解析器-您可以尝试所述步骤并
@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"))
                )
            )));
    }
}