私は既存のMVC Webアプリケーションの単体テストを作成しようとしています。その中で私はオートマッパー(IMapper
)のいくつかの問題に直面しています。マップ機能を使用しているときはいつでも、それはnull
の値を返します。コントローラーでAutomapper(IMapper)をモックする方法
私のコントローラコード:
public class UserAdministrationController : BaseController
{
private readonly iUserService _userService;
private readonly IMapper _mapper;
public NewsController(iUserService userService, IMapper mapper)
{
_userService = userService;
_mapper = mapper;
}
public ActionResult Create(int CompanyID == 0)
{
UserDetail data = _userService(CompanyID);
var Modeldata = _mapper.Map<UserDetailViewModel, UserDetail>(data);
return View(Modeldata);
}
}
モックマッピングコード:
public class MappingDataTest : CommonTestData
{
public Mock<IMapper> MappingData()
{
var mappingService = new Mock<IMapper>();
UserDetailViewModel interview = getUserDetailViewModel(); // get value of UserDetailViewModel
UserDetail im = getUserDetail(); // get value of UserDetails
mappingService.Setup(m => m.Map<UserDetail, UserDetailViewModel>(im)).Returns(interview);
mappingService.Setup(m => m.Map<UserDetailViewModel, UserDetail>(interview)).Returns(im);
return mappingService;
}
}
モッキングコード:
[TestClass]
public class UserAdminControllerTest
{
private MappingDataTest _common;
[TestInitialize]
public void TestCommonData()
{
_common = new MappingDataTest();
}
[TestMethod]
public void UserCreate()
{
//Arrange
UserAdministrationController controller = new UserAdministrationController(_common.mockUserService().Object, _common.MappingData().Object);
controller.ControllerContext = _common.GetUserIdentity(controller);
// Act
ViewResult newResult = controller.Create() as ViewResult;
// Assert
Assert.IsNotNull(newResult);
}
}
マッパーが、常にコントローラにnull
値を示す機能していません。親切に私を助けてください。前もって感謝します。
"なぜ私は必要なのですか?" Automapperは、マッピング設定が正しいことをアサートすることができます。おそらくあなたのユーザーサービスはテストされています。したがって、コントローラをテストする必要はありません。 – Mardoxx
ああいいです。これは、彼らがコントローラの単体テストを行うよう依頼する私のクライアント要件です。 httppostにいくつかの追加機能があるかもしれないので、私は親切にこれを手伝ってやる必要があります。 – Dinesh