使用@Autowired和JMockit使@Autowired对象为null

时间:2011-08-08 14:15:41

标签: unit-testing spring spring-mvc junit jmockit

我意识到还有另一个SO问题可以处理这个确切的问题(here)。但是,它不适用于我的情况。

我有一个使用spring的maven(web / frontend)项目。我通过pom将jmock添加到jvm:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.9</version>
  <configuration>
    <argLine>-javaagent:${settings.localRepository}/mockit/jmockit/0.998/jmockit-0.998.jar</argLine>
    <useSystemClassLoader>true</useSystemClassLoader>
    <forkMode>always</forkMode>
  </configuration>
</plugin>

SUT(缩写)如下:

@Service
@RequestMapping("/bars")
public class BarsController{
[...]
@Autowired
private FooUtils fooUtils;

[...]    
@RequestMapping(value = "/get", method = RequestMethod.POST)
public ModelAndView getBars(){
    ModelAndView mav = new ModelAndView();
    Session session = fooUtils.getSession();
[...]

现在,我真的想在我的测试中模拟FooUtils实例。按照this SO question中给出的建议,我尝试了:

@RunWith(JMockit.class)
public class BarsControllerTest {

@Autowired BarsController unitUnderTest;
@Mocked Session session;

@Before
public void setUp()
{
    FooUtils foo = new MockUp <FooUtils>() {
        @Mock
        Session getSession() {
            return session;
        }
    }.getMockInstance();

    mockit.Deencapsulation.setField(unitUnderTest, foo);
}

唉,unitUnderTestfoo都是null,导致这种情况发生:

java.lang.NullPointerException
    at net.manniche.thebars.BarsControllerTest.setUp(BarsControllerTest.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:172)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:78)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:70)
  • 这是非常意外的,因为我希望new MockUp<...>{}.getMockInstance()能够返回某些对象。

我想我只是错过了一些关键部分,但是哪个?

0 个答案:

没有答案
相关问题