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 に答える