如何在Spring Hateos中为ResourceAssembler编写mockito测试用例?

时间:2016-04-24 04:29:45

标签: spring-mvc mockito spring-hateoas

我正在尝试为下面的汇编程序编写一个单元测试,但我一直在 无法通过RequestContextHolder找到当前请求。这是从Spring MVC处理程序调用的吗? 。我想知道如何模拟资源创建?

@Component
    public class LoginResourceAssembler extends ResourceAssemblerSupport<User, ResourceSupport> {

        public LoginResourceAssembler() {

            super(User.class, ResourceSupport.class);
        }

        @Override
        public ResourceSupport toResource(User user) {

            ResourceSupport resource = new ResourceSupport();
            final String id = user.getId();

            resource.add(linkTo(MyAccountsController.class).slash(id).slash("accounts").withRel("accounts"));

            return resource;
        }

    }

2 个答案:

答案 0 :(得分:5)

您可以执行以下操作,而不是从普通单元测试更改为IMO集成测试(给定Spring框架的依赖项),您可以执行以下操作:

@RunWith(MockitoJUnitRunner.class)
public class LoginResourceAssemblerTest {
    @InjectMocks
    private LoginResourceAssembler loginResourceAssembler;

    @Before
    public void setup() {
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
    }

    @Test
    public void testToResource() {
        //...
    }
}

答案 1 :(得分:3)

我看到错误无法通过RequestContextHolder找到当前请求。这是从Spring MVC处理程序调用的,因为我的测试类是用@RunWith(MockitoJUnitRunner.class)注释的,而这并没有注入控制器。 为了解决这个错误,我用

注释了我的测试用例
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration

我案例中的工作测试用例

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration

public class LoginResourceAssemblerTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @InjectMocks
    private LoginResourceAssembler loginResourceAssembler;

    @Before
    public void setUp() {

        initMocks(this);
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    }

    @Test
    public void testToResource() {
        User user = new User();
        user.setId("1234");
        ResourceSupport resource = loginResourceAssembler.toResource(user);
        assertEquals(1,resource.getLinks().size());
        assertEquals("accounts",resource.getLinks().get(0).getRel());
                assertTrue(resource.getLinks().get(0).getHref().contains("accounts"));

    }

}