Java Testng 单元测试:Spring 无法在 BeforeSuite 或 BeforeTest 之前创建对象

Java Testng unit test: Spring is not able to create object before BeforeSuite or BeforeTest

我有一个单元测试在当前格式下运行良好。我的单元测试看起来像:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

@Test
@ContextConfiguration(locations = { "classpath:testContext.xml" })
public class DialPadMonitorTest extends AbstractTestNGSpringContextTests
{
    @Autowired
    DialPadMonitor service;


    @BeforeSuite
    public void doBeforeSuite() {       
        System.out.println("Initializing suit.........");
    }

    @BeforeTest
    public void doBeforeTest() {
        System.out.println("Initializing tests.........");
    }

    @Test()
    void testIfEasyToDial()
    {
        service.createDialAssociation();

        Assert.assertTrue(service.isNumberEasy(159658521));
        Assert.assertTrue(service.isNumberEasy(555555555));
        Assert.assertFalse(service.isNumberEasy(505555555));
        Assert.assertFalse(service.isNumberEasy(555555505));

        Assert.assertTrue(service.isNumberEasy(2547096));
        Assert.assertTrue(service.isNumberEasy(5547521));
        Assert.assertFalse(service.isNumberEasy(2806547));
        Assert.assertFalse(service.isNumberEasy(3558123));

    }

    @Test()
    void testIfAssociated()
    {
        service.createDialAssociation();

        Assert.assertTrue(service.isNoAssociated(3,3));
        Assert.assertTrue(service.isNoAssociated(3,6));
        Assert.assertFalse(service.isNoAssociated(3,9));

    }
}

尽管我看到了像

这样的评论

问题是,如果我将 service.createDialAssociation() 移动到 BeforeSuite 或 BeforeTest 中的任何一个,我将收到空指针异常。

关于为什么我在这种情况下会出现空指针异常以及如何解决的任何见解?

如果要确保 Spring 上下文已完全加载,请添加一个带有 @PostConstruct

注释的方法

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization

你应该使用 @BeforeMethod 而不是 @BeforeTest 因为上下文是这样初始化的。您可以在 Spring source file.

中看到它