捕获异常并使用 C# Nunit 断言它
Catch the exception and assert it using C# Nunit
我正在做一个阴性测试,我期待得到一个例外。所以我只想知道如何捕获异常消息然后断言它。
[Then(@"I create the (.*)")]
public void ThenICreateTheContact(string entityName)
{
entityId = m_OrgServ.Create(entity);
}
[Then(@"I verify the exception")]
public void ThenIVerifyTheException()
{
ScenarioContext.Current.Pending();
}
这是个例外 -
Generic Exception caught: contact With Id = 81b10448-49b2-ea11-aacb-067e3e789e92 Does Not ExistSystem.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Generic Exception caught: contact With Id = 81b10448-49b2-ea11-aacb-067e3e789e92 Does Not Exist (Fault Detail is equal to Exception details:
我做m_OrgServ.Create(entity)时出现异常;
所以我想捕获它,然后在我展示的下一个方法中断言它的消息。
您可以使用 TestDelegate。
private TestDelegate _create;
[Then(@"I create the (.*)")]
public void ThenICreateTheContact(string entityName)
{
_create = () => m_OrgServ.Create(entity);
}
[Then(@"I verify the exception")]
public void ThenIVerifyTheException()
{
var exception = Assert.Throws<FaultException<OrganizationServiceFault>>(_create);
Assert.That(exception.Message, Is.EqualTo("expected message here"));
}
我正在做一个阴性测试,我期待得到一个例外。所以我只想知道如何捕获异常消息然后断言它。
[Then(@"I create the (.*)")]
public void ThenICreateTheContact(string entityName)
{
entityId = m_OrgServ.Create(entity);
}
[Then(@"I verify the exception")]
public void ThenIVerifyTheException()
{
ScenarioContext.Current.Pending();
}
这是个例外 -
Generic Exception caught: contact With Id = 81b10448-49b2-ea11-aacb-067e3e789e92 Does Not ExistSystem.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Generic Exception caught: contact With Id = 81b10448-49b2-ea11-aacb-067e3e789e92 Does Not Exist (Fault Detail is equal to Exception details:
我做m_OrgServ.Create(entity)时出现异常; 所以我想捕获它,然后在我展示的下一个方法中断言它的消息。
您可以使用 TestDelegate。
private TestDelegate _create;
[Then(@"I create the (.*)")]
public void ThenICreateTheContact(string entityName)
{
_create = () => m_OrgServ.Create(entity);
}
[Then(@"I verify the exception")]
public void ThenIVerifyTheException()
{
var exception = Assert.Throws<FaultException<OrganizationServiceFault>>(_create);
Assert.That(exception.Message, Is.EqualTo("expected message here"));
}