繁体   English   中英

Java Testng 单元测试:Spring 无法创建 ZA8CFDE6331BD59EB2AC96F8911C4B6666 之前

[英]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));

    }
}

即使我看到这样的评论

  • System.out.println("初始化套装......");
  • System.out.println("正在初始化测试......");

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

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

如果要确保Spring上下文已完全加载,请添加一个用@PostConstruct注释的方法

PostConstruct批注用于需要依赖注入完成以执行任何初始化之后需要执行的方法上

您应该使用@BeforeMethod而不是@BeforeTest因为上下文是通过这种方式初始化的。 您可以在Spring源文件中看到它。

添加

 @BeforeSuite(alwaysRun = true)
 @BeforeClass(alwaysRun = true)
 @Override
 protected void springTestContextPrepareTestInstance() throws Exception {
     super.springTestContextPrepareTestInstance();
 }

解决了这个问题。 请注意,此方法 springTestContextPrepareTestInstance 应在所有 @BeforeSuite 方法之前执行。 这可以通过将其放置到单独的基础 class 或通过在其他 @BeforeSuite 注释中添加 depenedsOn 来实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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