Sahil Chabria
Sahil Chabria

Reputation: 13

NullPointerException when Testing Service and DAO class JUnit

I am testing a DAO class using JUnit and I am getting a nullpointerexception which I am not sure why as I am initiating the service class. The following is the test class:

public class RegisterTest {

private UserDaoImpl userservice = new UserDaoImpl();

@Mock
JdbcTemplate jdbcTemplate;

 User user;

@Before
public void setUp() {
  user = new User();
}

@Test
public void testSetAddress() {
    user.setAddress("A");
    assertEquals(user.getAddress(), "A");
}
@Test 
public void testSetEmail() {
    user.setEmail("B");
    assertEquals(user.getEmail(), "B");
}
@Test 
public void testSetFirstname() {
    user.setFirstname("C");
    assertEquals(user.getFirstname(), "C");
}
@Test 
public void testSetLastname() {
    user.setLastname("D");
    assertEquals(user.getLastname(), "D");
}
@Test 
public void testSetPassword() {
    user.setPassword("E");
    assertEquals(user.getPassword(), "E");
}
@Test 
public void testSetUsername() {
    user.setUsername("F");
    assertEquals(user.getUsername(), "F");
}
@Test
public void testRegister() {
    userservice.register(user);
    String username = user.getUsername();
    assertEquals(userservice.findByUsername(username), 1);
}
}

The following is the UserDaoImpl

public class UserDaoImpl implements UserDao {
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
DataSource datasource;
@Autowired
JdbcTemplate jdbcTemplate;

 public List<User> findByUsername(String username) {

  String sql = "select * from users where username='" + username + 
"'";
  List<User> users = jdbcTemplate.query(sql, new UserMapper());
  return users;
}

public int register(User user) {
// If username is unique
String uniqueusername = "select * from users where username='" + 
user.getUsername() + "'";
List<User> users = jdbcTemplate.query(uniqueusername, new 
UserMapper());
if(users.size() == 0) {
      // encode password
      String encryptedPassword = 
passwordEncoder.encode(user.getPassword());
      // Updating database with new user
      String sql = "insert into users values(?,?,?,?,?,?)";
      return jdbcTemplate.update(sql, new Object[] { 
        user.getUsername(), 
        encryptedPassword,
        user.getFirstname(),
        user.getLastname(), 
        user.getEmail(), 
        user.getAddress() });
      }

else {
    return 0;
}
  }

How can I inject the class in the test class? I guess the reason why the nullpointerxeception is because the dao class is not being injected properly in the test class

Upvotes: 0

Views: 1184

Answers (1)

CodeScale
CodeScale

Reputation: 3304

You should run your test with adequate runner

RunWith(MockitoJunitRunner.class)
public class RegisterTest {

Then you need to inject your mock inside the DAO

@InjectMocks
private UserDaoImpl userservice = new UserDaoImpl();

Upvotes: 1

Related Questions