简体   繁体   中英

How to mock Session object in java

I have created a method, in which i am using JaloSession. I am writing a Junit test for this. Please let me know how can i mock the following.

ABC abc = JaloSession.getCurrentSession.getAttribute("abc");

Thanks in advance.

With powermock you can mock the static call:

mockStatic(JaloSession.class);

expect(JaloSession.getCurrentSession()).andReturn(yourMock);

...etc

However you don't need to do that. Perhaps the easiest thing since you control the code is to wrap this method call in a protected method

protected ABC getAbc(){
     return JaloSession.getCurrentSession.getAttribute("abc");
}

And then in your tests, make a subclass of your class that overrides getAbc() to return a different ABC instance.

@Test
public void myTest(){
     final ABC mockAbc = ....

     Foo foo = new Foo(){
          @Override
          protected ABC getAbc(){
             return mockAbc;
          }
     };

     //do test on Foo
}

You can't (easily) because of the static call.

So either pass the current session in to the function you are testing, or define an interface for getting the current session and pass that to your object's constructor. In production implement it to call the static nmethod, and in test either mock it or build a fake.

As a bonus you will end up with a cleaner design, where dependencies are passed in from above instead of directly accessed at the lowest levels.

With the JMockit mocking library, you can mock it as follows:

@Test
public void mockJaloSession(@Mocked final JaloSession jalo) {
    final ABC testABC = new ABC();
    new Expectations() {{ jalo.getAttribute("abc"); result = testABC; }};

    // From code under test:
    ABC abc = JaloSession.getCurrentSession().getAttribute("abc");

    assertSame(testABC, abc);
}

(The test doesn't need to worry about the getCurrentSession() call as it will automatically return the mock jalo object.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM