Question

I am still a beginner in Spring . I have one test class as below an run by TestNG ...

@Service("springTest")
public class SpringTest {
  private MyService myService;

  @Autowired
  public void setMyService(MyService myService) {
    this.myService = myService;
    // below was ok , nothing error
    System.out.println(myService.getClass());
  }

  //org.testng.annotations.Test
  @Test
  public void doSomethingTest() {
    load();
    // That may cause NullPointerException
    myService.doSomething();
  }

  private void load(){
  // here codes for load spring configuration files
  }
}

So , I have no idea why myService.doSomething(); produce NullPointerException ? Can someone give me suggestions what I need to do ? What problem may cause this error ? What am I wrong ? Now I am using as ...

@Service("springTest")
public class SpringTest {
  private static MyService myService;

  @Autowired
  public void setMyService(MyService myService) {
    SpringTest.myService = myService;
    System.out.println(myService.getClass());
  }
  //org.testng.annotations.Test
  @Test
  public void doSomethingTest() {
    load();
    // fine , without error
    myService.doSomething();
  }

  private void load(){
  // here codes for load spring configuration files
  }
}

PS: I think I don't need to show my spring configuration file , because it is really simple and I believe that will not be cause any error. So , I left it to describe. But if you want to see , I can show you. And then please assume my spring configurartion file was loaded properly and this was loaded before my Test classes run. Thanks for reading my question.By the way, I can't also use field injection and I can only use setter method injection.

Was it helpful?

Solution

Just remove the static initializer. Keep setter injection (I prefer it).

Use your first example, the second code is wrong - don't use it.

Make sure you tests are being run by spring (and therefore the bean is initialized correctly by spring).

The null pointer is caused by running the test method before spring has initialized the bean.

You need somethign like this

@RunWith (SpringJUnit4ClassRunner.class)
@ContextConfiguration (locations = "classpath:/config/applicationContext-test.xml")
public class SpringTest {...}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top