How to write a mockito test case for ResourceAssem

2019-07-27 03:06发布

问题:

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

    }

}