我必须在以下场景中为抽象基类方法编写测试用例:
public abstract class baseclass{
public bool MyBaseMethod(){
if(User.Identity.IsAuthenticate)
{.....}
}
}
public class deriveclass: baseclass{
}
在我的测试夹具类中,我的测试方法为:
[Test]
public void MyBaseMethodtest()
{
SetUserIdentity(true);
var obj = new deriveclass();
var result = obj.MyBaseMethod();
//test cases follows
..........
}
private void SetUserIdentity(bool login = false)
{
var identity = new Mock<ClaimsIdentity>() { DefaultValue = DefaultValue.Mock };
if (login)
{
identity.Setup(p => p.IsAuthenticated).Returns(true);
}
var principal = new ClaimsPrincipal(identity.Object);
var httpContext = new Mock<HttpContextBase> { DefaultValue = DefaultValue.Mock };
httpContext.SetupGet(x => x.User).Returns(principal);
controller.ControllerContext = new ControllerContext(httpContext.Object, new RouteData(), controller);
}
但是当我尝试引用 MyBaseMethod 时,它会为 User 对象提供空引用错误。我相信这正在发生,因为我正在为派生类而不是基类设置控制器上下文。我试图用谷歌搜索类似的场景,但找不到。