3

现在对于单元测试,我需要验证方法来假装它工作正常,在我的情况下什么都不做,所以我可以测试方法本身是否完成了预期的工作(根据单元测试原则在其他地方测试了身份验证,但是身份验证需要在该方法中调用)

这是我的 TestNG 类,我需要为身份验证制作模拟对象:

package in.hexgen.api.facade;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.testng.annotations.Test;

import com.hexgen.api.facade.security.HexGenPermissionEvaluator;

public class HexGenPermissionEvaluatorTest {
     private static final Logger logger = LoggerFactory.getLogger(HexGenPermissionEvaluatorTest.class);

  Object name="akash";
  Object permission="CREATE_REQUISITION";
  Authentication authentication;

  //@Resource(name = "permissionEval")
  private HexGenPermissionEvaluator permissionEval;

  @Test
  public void hasPermission() {
      //authentication.setAuthenticated(true);

      logger.debug("HexGenPermissionEvaluator Generate - starting ...");
         permissionEval.hasPermission(authentication,name, permission);
      logger.debug("HexGenPermissionEvaluator Generate - completed ...");
  }

}

这个怎么做。

此致

4

2 回答 2

5

考虑到permissionEval对象调用authentication.isAuthenticatedFor(name,permission),使用 Mockito ( https://code.google.com/p/mockito/ ):

import static org.mockito.Mockito.*

...

@Test
public void test(){
    // Given
    Authentication authentication = mock(Authentication.class);
    when(authentication.isAuthenticatedFor(eq(name),eq(permission)).thenReturn(true);

    // When
    permissionEval.hasPermission(authentication,name, permission);

    // Then
    // Do you asserts/verify
}
于 2013-03-20T11:19:37.660 回答
1

您可以像这样在 @Test 方法上方添加 @WithMockUser

@Test
@WithMockUser(username = "user1", password = "user1", authorities = {
        "ROLE_ADMIN" })
public void testDeleteUser() throws Exception {
    User currentUser = createUser(1L, new Role(1L, "admin"));
    User userForDelete = createUser(2L, new Role(2L, "user"));
    when(userDaoMock.findByLogin(currentUser.getLogin()))
            .thenReturn(currentUser);
    mockMvc.perform(get("/admin/delete/{id}", userForDelete.getId()))
            .andExpect(status().is3xxRedirection())
            .andExpect(redirectedUrl("/admin"));
}
于 2016-12-23T15:46:52.357 回答