Java.lang.NullPointerException while creating object

My application is using spring struts and frames. I have a class FormA

that has an autwired property. When I try to instantiate it while writing unit tests, I get a Null Pointer exception. Here is my code.

My ClassA:

public class FormA{
    private String propertyOne;
    @Autowired
    private ServiceClass service;

    public FormA(){
    }
}

      

My unit test method:

@Test
public void testFormA(){
FormA classObj = new FormA();    
}

      

+3


source to share


2 answers


@Autowired

only works when the object lifecycle is managed by Spring.



You will need to run your tests with @RunWith(SpringJUnit4ClassRunner.class)

, and instead of FormA

manually instantiating it, add it to the test class as well using @Autowired

.

+3


source


When you instantiate an object in a new way, autowire \ inject doesn't work ...

as a workaround, you can try this:

create your NotesPanel bean template

<bean id="notesPanel" class="..." scope="prototype">
    <!-- collaborators and configuration for this bean go here -->
</bean>

      

and create it this way

applicationContext.getBean("notesPanel");

      



PROTOTYPE . This allows you to define one bean definition for any number of object instances.

anyway a unit test should be

Test class

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {

    @Autowired
    private UserService userService;

    @Test
    public void testName() throws Exception {
        List<UserEntity> userEntities = userService.getAllUsers();

        Assert.assertNotNull(userEntities);
    }
}

      

OWN spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="userService" class="java.package.UserServiceImpl"/>

</beans>

      

+1


source







All Articles