How to write a mockito test case for ResourceAssembler with in Spring Hateos?

回眸只為那壹抹淺笑 提交于 2019-12-24 06:03:58

问题


I am trying to write a unit test for the below Assembler but i keep getting Could not find current request via RequestContextHolder. Is this being called from a Spring MVC handler?. I wanted to know how i can mock out the resource creation?

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

    }

回答1:


Instead of changing from a plain unit test to a IMO integration test (given dependency of the spring framework) you could do something like:

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

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

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



回答2:


I was seeing the error Could not find current request via RequestContextHolder. Is this being called from a Spring MVC handler because my test class was annotated with @RunWith(MockitoJUnitRunner.class) and this was not injecting the controller. To fix this error, i annotated my test case with

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

A working test case in my case

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

    }

}


来源:https://stackoverflow.com/questions/36819299/how-to-write-a-mockito-test-case-for-resourceassembler-with-in-spring-hateos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!