I have an unit test is working fine in it's current format. My unit test looks like:
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));
}
}
Even though I am seeing the comments like
Problem is that if I move service.createDialAssociation() into any of BeforeSuite or BeforeTest, I am getting null pointer exception.
Any insight on why am I getting the null pointer exception in that case and how to solve?
If you want to make sure Spring context was loaded fully, add a method anotated with @PostConstruct
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization
You should use @BeforeMethod
instead of @BeforeTest
because context is initialized that way. You can see it in a Spring source file .
Adding
@BeforeSuite(alwaysRun = true)
@BeforeClass(alwaysRun = true)
@Override
protected void springTestContextPrepareTestInstance() throws Exception {
super.springTestContextPrepareTestInstance();
}
solves the issue. Note that this method springTestContextPrepareTestInstance should be executed before all @BeforeSuite methods. This can be achieved by placing it to a separate base class or by adding depenedsOn in others @BeforeSuite annotations.
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.