문제

There is a servlet i want to test , servlet have session and puts "loginBean" (which contain logged in user related info) inside session , which i have mocked already and working fine , now IN GUI level , there are 2 tab , DetailSet1 , detailsSet2 , when u enter data of DetailSet1 , it get saved in session and also does some business logic , now it comes to DetailsSet2 , you already have DetailSet1 in session , so it got all it needs , data is saved in DB. Now it's obvious i have to mock HttpSession because i am running unit cases from outside the container , but data which gets stored is also in HttpSession , if i mock those as well , it defeats the purpose of testing. so my Question is , i need HttpSession object to return mocked data for what i have it mocked for and it is suppose to act like any normal HttpSession object for other cases. Like , if code does session.setAttribute("name","Vivek") , then session.getAttribute("name") should return "Vivek" after that , but in case of mocked object it return "NULL" why? because i haven't mocked behaviour for "getAttribute("name").

In simple word Partial mocking for HttpSession or Interfaces.

도움이 되었습니까?

해결책

HttpSession is an interface, so you'll need to either write your own implementation of it, or mock it. I would recommend mocking it with Mockito, then stubbing getAttribute and setAttribute to delegate to a HashMap, or some other suitable structure.

So in your test class, you'll have fields for

  • your mocked HttpSession,
  • a real HashMap<String,Object>

and you'll use Answer<Object> objects for each of getAttribute and setAttribute. Each Answer will just delegate the call off to the HashMap.

You could set all this up either in a @Before method, or in a @Test method like this.

@Mock private HttpSession mockHttpSession;
Map<String,Object> attributes = new HashMap<String,Object>();

@Test
public void theTestMethod() {

    Mockito.doAnswer(new Answer<Object>(){
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            String key = (String) invocation.getArguments()[0];
            return attributes.get(key);
        }
    }).when(mockHttpSession).getAttribute(anyString());

    Mockito.doAnswer(new Answer<Object>(){
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            String key = (String) invocation.getArguments()[0];
            Object value = invocation.getArguments()[1];
            attributes.put(key, value);
            return null;
        }
    }).when(mockHttpSession).setAttribute(anyString(), any());

다른 팁

The Spring Testing framework includes MockHttpSession. It is available via Maven:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.0.1.RELEASE</version>
</dependency>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top