尝试在测试中创建用户帐户。但是,运行它时,获取对象引用并未设置为对象错误的实例。
这是我的MemberShip提供程序类,它位于类库MyCompany.MyApp.Domain.dll中:
using System;
using System.Collections.Generic;
using System.Web.Security;
namespace MyCompany.MyApp.Domain
{
public class MyMembershipProvider : SqlMembershipProvider
{
const int defaultPasswordLength = 8;
private int resetPasswordLength;
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
resetPasswordLength = defaultPasswordLength;
string resetPasswordLengthConfig = config["resetPasswordLength"];
if (!String.IsNullOrEmpty(resetPasswordLengthConfig))
{
config.Remove("resetPasswordLength");
if (!int.TryParse(resetPasswordLengthConfig, out resetPasswordLength))
{
resetPasswordLength = defaultPasswordLength;
}
}
base.Initialize(name, config);
}
public override string GeneratePassword()
{
return Utils.PasswordGenerator.GeneratePasswordAsWord(resetPasswordLength);
}
}
}
这是我的App.Config,用于我的单独测试类库MyCompany.MyApp.Doman.Test.dll,它引用了我上面的业务域库:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SqlServer" connectionString="data source=mycomp\SQL2008;Integrated Security=SSPI;Initial Catalog=myDatabase" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="MyMembershipProvider"
type="MyCompany.MyApp.Domain.MyMembershipProvider,MyCompany.MyApp.Domain"
connectionStringName="SqlServer"
applicationName="MyApp"
minRequiredNonalphanumericCharacters="0"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed"/>
</providers>
</membership>
</system.web>
</configuration>
这是抛出“对象引用未设置为对象实例”的方法
public class MemberTest
{
public static void CreateAdminMemberIfNotExists()
{
MembershipCreateStatus status;
status = MembershipCreateStatus.ProviderError;
MyMembershipProvider provider = new MyMembershipProvider();
provider.CreateUser("Admin", "password", "someone@somewhere.co.uk", "Question", "Answer", true, Guid.NewGuid(), out status);
}
}
它会抛出provider.CreateUser行
答案 0 :(得分:2)
我很确定你应该在调用CreateUser之前在测试代码中调用provider.Initialize(...)。
答案 1 :(得分:1)
嗯,没有人有答案。虽然初始化是问题,但csgero在正确的轨道上。但只是直接调用它不是一个解决方案。这有效:
public class MemberTest
{
public static void CreateAdminMemberIfNotExists()
{
MembershipCreateStatus status;
MembershipUser member = Membership.CreateUser("Admin", "password", "email@somewhere.co.uk", "Question", "Answer", true, out status);
}
}
我认为直接实例化我的会员提供者需要设置通常存储在app.config或web.config中的配置属性,然后调用initialize。但是,在Mebership类上调用静态CreateUser方法会导致读取配置,然后解析,加载和初始化配置中指定的类型。
答案 2 :(得分:0)
错误是直接在provider.CreateUser上还是在其中的堆栈中 - 也许你可以在调用之前检查null。
也许缺少一种依赖性 - 你有没有相关的DB dll?