如何使用Mockito模拟PreparedStatement

z18hc3ub  于 2023-06-05  发布在  其他
关注(0)|答案(1)|浏览(549)

我有以下函数,它可以更改MySQL数据库中用户的用户名:

public User changeUsername (ChangeUsername ChangeUsername) {
    // Getting user from database
    String sql = "select * from users where username='" + ChangeUsername.getUsername() + "'";
    List<User> users = jdbcTemplate.query(sql, new UserMapper());
    User user = users.get(0);
    // Getting encoded password from database
    String encodedPassword = user.getPassword();
    // Getting password input from user
    String rawPassword = ChangeUsername.getPassword();
    // Comparing passwords
    boolean isPasswordMatch = passwordEncoder.matches(rawPassword, encodedPassword);
    // If password matches
    if(isPasswordMatch){
        // Getting current userrname
        String username = ChangeUsername.getUsername();
        // Getting new username
        String newusername = ChangeUsername.getNewusername();
        // Updating username in database with prepared statement
        String update = "update users set username = ? where username = ?";
        Connection conn;
        try {
            conn = datasource.getConnection();
            PreparedStatement preparedStatement = conn.prepareStatement(update);
            preparedStatement.setString(1, newusername );
            preparedStatement.setString(2, username);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
    return null;
   }

我尝试使用Mockito和JUnit 5测试函数,但是在调用assertEquals检查用户名是否在测试代码中成功更改时出现Assert错误。因此,在测试函数时,用户名未正确更改。下面是我的测试代码:

@RunWith(MockitoJUnitRunner.class)
public class ChangeUsernameTest {

    UserDaoImpl userdaoimpl = mock(UserDaoImpl.class);
    UserDao userdao = mock(UserDao.class);
    @Mock
    JdbcTemplate jdbcTemplate;
    @Mock
    private PreparedStatement stmt;
    @Mock
    private Connection c;
    @Mock
    private DataSource ds;
    @Mock
    ChangeUsername changeusername;
    @Mock
    User user;
    @BeforeEach
    public void setUp() {
      MockitoAnnotations.initMocks(this);
      user = new User();
      changeusername = new ChangeUsername();
      try {
            when(c.prepareStatement(any(String.class))).thenReturn(stmt);
            when(ds.getConnection()).thenReturn(c);
            doNothing().when(stmt).setString(any(int.class), any(String.class));
            when(stmt.execute()).thenReturn(Boolean.TRUE);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Test
    public void setUserDetails() {
        user.setAddress("A");
        user.setEmail("B");
        user.setFirstname("C");
        user.setLastname("D");
        user.setPassword("E");
        user.setUsername("F");
    }
    @Test
    public void testSetUsername() {
        changeusername.setUsername("F");
        assertEquals(changeusername.getUsername(), "F");
    }
    @Test
    public void testSetPassword() {
        changeusername.setUsername("E");
        assertEquals(changeusername.getUsername(), "E");
    }
    @Test
    public void testSetNewUsername() {
        changeusername.setNewusername("X");
        assertEquals(changeusername.getNewusername(), "X");
    }
    @Test
    public void testChangeUsername() {
        int update = jdbcTemplate.update(any(String.class), any(Object.class));
        when(userdaoimpl.register(user)).thenReturn(update);
        userdaoimpl.register(user);
        when(userdaoimpl.changeUsername(changeusername)).thenReturn(user);
        userdaoimpl.changeUsername(changeusername);
        assertEquals("X", user.getUsername());
    }
}
o8x7eapl

o8x7eapl1#

//USE PowerMockito it is easy as shown below



@RunWith(PowerMockRunner.class)
@PrepareForTest({yourtarget.class,datasource.class})
public class DBTest {

    @Mock
    private Connection con;

    @Mock
    private PreparedStatement stmt;

    @Mock
    private ResultSet rs;

    @Before
    public void setUpBeforeClass() throws Exception {
        MockitoAnnotations.initMocks(this);

    }

    @Test
    public void testMethod() throws SQLException {
        PowerMockito.mockStatic( DataSource.class );
        try {
            when( DataSource.getConnection() ).thenReturn( con );
        } catch (Exception e) {
            e.printStackTrace();
        }
        when( con.prepareStatement( any()) ).thenReturn( stmt );
        when( stmt.executeUpdate() ).thenReturn( 1 );

    }

}

相关问题