标签: nunit

正确的例外测试方法

我在一个80%简单逻辑和20%复杂逻辑的项目上做TDD.如果certaing方法抛出错误并想知道正确的方法,我发现自己经常测试.我使用NUnit和JustMock.

我有两种方法可以做到这一点.使用ExpectedException属性,并指定类型.或写作如下.写下面的专业人员是我也可以断言exception.message(如果我已经自定义了),如果测试失败,我也会得到例外消息.但是我想和别人一起检查你是怎么做的.总结一下:

  1. 对这样的异常进行大量测试是否正常?
  2. 这是正确的方法:

只是解释:供应商提供某些合同,部门接受一份合同但不能与同一供应商签订一份以上的合同(但是cource可以与不同的供应商签订不同的合同)

    [Test]
    public void Accepting_more_than_one_contract_from_supplier_throws_exception()
    {
        //Arrange
        var department = new Department(Guid.NewGuid(), "1234");
        var supplier = Mock.Create<Supplier>();
        var contract1 = Mock.Create<DeliveryContract>();
        var contract2 = Mock.Create<DeliveryContract>();
        var id = Guid.NewGuid();
        supplier.Arrange(x => x.Id).Returns(id);
        contract1.Arrange(x => x.Supplier).Returns(supplier);
        contract2.Arrange(x => x.Supplier).Returns(supplier);

        //Act
        department.AcceptContract(contract1);

        //Assert
        try
        {
            department.AcceptContract(contract2);
            Assert.Fail("Duplicate contract with supplier did not throw an exception");
        }
        catch (Exception ex)
        {   
            Assert.AreEqual(typeof(ArgumentException),ex.GetType(),ex.Message);
        }
    }
Run Code Online (Sandbox Code Playgroud)

c# tdd nunit unit-testing domain-driven-design

0
推荐指数
1
解决办法
1133
查看次数

问题与Assert.Throws NUnit测试中的异常

我是第一次尝试NUnit,单元测试和集成测试.我一直在阅读和做很多在线课程.因为我相信你非常清楚这是理解理论并在实践中做到的事情.

我被困在一个特定的测试上.我的应用程序是在C#.Net 3.5中.

我试图断言具有某个错误输入的方法将抛出特定异常.当我使用给测试的相同输入运行方法时,抛出预期的异常.

被测试的方法是:

 private static bool FilePathHasInvalidChars(string userInputPath)
{
    try
    {
        Path.GetFullPath(userInputPath);//this is where the warning appears

    }
    catch (Exception e)
    {
        Log.Error(String.Format(
            "The Program failed to run due to invalid characters or empty string value for the Input Directory. Full Path : <{0}>. Error Message : {1}.",
            userInputPath, e.Message), e);
        return true;

    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

我想检查上面的代码是否可以捕获异常,如果提供的输入目录不符合条件.

我目前的单元测试是:

    [Test]
    public void can_throws_exception_for_empty_string()
    {
        var testDirectory = "";
        var sut = new DirectoryInfoValidator();

        Assert.Throws<ArgumentNullException>(() => sut.FilePathHasInvalidChars(testDirectory));
    }
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是测试总是失败,如果我检查返回它说明它期望一个ArgumentNull异常但是为null.我从测试中截取了输出的截图: …

c# integration-testing nunit unit-testing exception-handling

0
推荐指数
1
解决办法
2872
查看次数

将Enum值与Integer进行比较 - Assert.AreEqual

我对枚举进行了以下测试:

[TestCase]
public void NoneIsDefaultTest()
{
    Assert.AreEqual(0, Command.None);
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是确保枚举的任何添加都不会更改默认值.但是,测试失败了:

Expected: 0
But was:  None
Run Code Online (Sandbox Code Playgroud)

是Assert.AreEqual自动应用.ToString()?我怎么能避免这个?

编辑:枚举定义:

internal enum Command { None = 0, Build, Config, Reconfig, Help, Version }
Run Code Online (Sandbox Code Playgroud)

c# enums nunit

0
推荐指数
1
解决办法
746
查看次数

c#中两个单元测试之间的依赖关系

假设我们有两个相互依赖的单元测试.TestA依赖于TestB.现在我们想要更改代码,这样当我们运行TestA时,TestB将自动运行.

[TestMethod]
public void TestA()
{
    string id = "123456789";
    NewUser user = new NewUser();
    Boolean idCheck = user.checkID(id);
    Assert.IsFalse(idCheck);

}


[TestMethod]
[HostType("ASP.NET")]
[UrlToTest("http://localhost:1776/Login.aspx")]
[AspNetDevelopmentServerHost("$(SolutionDir)\\project", "/")]
public void TestB()
{
    Page page = _testContextInstance.RequestedPage;
    Button button = page.FindControl("BNewUser") as Button;
    PrivateObject po = new PrivateObject(page);
    po.Invoke("BNewUser_Click", button, EventArgs.Empty);
    Assert.IsFalse(page.Visible);

}
Run Code Online (Sandbox Code Playgroud)

c# dependencies nunit unit-testing

0
推荐指数
1
解决办法
309
查看次数

针对Catch部分功能的Nunit测试用例

public int ReturnFromDB(int input)
{
    try
    {
         return repositorymethod(input);
    }
    catch(RepositoryException ex)
    {
         Throw new ParticularException("some message",ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

repositorymethod()使用select查询从db返回整数数据.

对于积极的情况,我可以断言返回值.但是这个方法在NCover中的代码覆盖率仍然是60%.

如何测试此方法的Catch部分?如何触发异常部分?即使我给出一个负值作为输入,返回0也不会触发异常.

c# nunit unit-testing ncover

0
推荐指数
1
解决办法
73
查看次数

Moq - 为简单的工厂创建的DTO界面创建内联假

我有一个简单的抽象工厂,返回一个简单的类型.基本上,它只是用数据填充类型并返回它,类似于DTO.

public interface IPagingInstructionFactory
{
    IPagingInstruction Create(int skip, int take, IProvider provider);
}

public interface IPagingInstruction
{
    int Skip { get; }
    int Take { get; }
    IProvider Provider { get; }
}
Run Code Online (Sandbox Code Playgroud)

我现在想要创建一个模拟工厂,它基本上与真实工厂做同样的事情 - 它从Create()方法传递参数并从IPagingInstruction实例的属性返回它们.

这是一个有效的例子:

var pagingInstructionFactory = new Mock<IPagingInstructionFactory>();
pagingInstructionFactory
    .Setup(x => x.Create(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<IProvider>()))
    .Returns((int skip, int take, IProvider provider) => 
        new FakePagingInstruction(skip, take, provider));


public class FakePagingInstruction
    : IPagingInstruction
{
    public FakePagingInstruction(
        int skip,
        int take,
        IProvider provider
        )
    {
        if (provider == null)
            throw …
Run Code Online (Sandbox Code Playgroud)

c# nunit unit-testing moq

0
推荐指数
1
解决办法
949
查看次数

如何对字符串扩展方法进行单元测试

我有一些如下代码,我想对字符串类的扩展方法进行单元测试:

public static string Replace(this string str, Dictionary<string, string> dict)
{            
}
Run Code Online (Sandbox Code Playgroud)

我的扩展方法在主项目中,因此我的单元测试项目甚至看不到它。

我怎样才能做到这一点?我正在使用Nunit。

c# nunit unit-testing

0
推荐指数
1
解决办法
1696
查看次数

如何为控制器使用automapper编写单元测试?

我正在尝试为控制器编写单元测试以测试方法返回所有用户.但我很困惑如何用automapper编写单元测试

控制器:

private readonly IUserService _userService;

public UserController(IUserService userService)
{
  this._userService = userService;
}

public ActionResult List()
{
  var users = _userService.GetAllUsers().ToList();
  var viewModel = Mapper.Map<List<UserViewModel>>(users);
  return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)

控制器测试:

    private Mock<IUserService> _userServiceMock;
    UserController objUserController;
    List<UserViewModel> listUser;

    [SetUp]
    public void Initialize()
    {
        _userServiceMock = new Mock<IUserService>();
        objUserController = new UserController(_userServiceMock.Object);
        listUser = new List<UserViewModel>()
        {
            new UserViewModel() {Id = 1, Active = true, Password = "123456", UserName = "hercules"},
            new UserViewModel() {Id = 2, Active = false, Password = "1234567", …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc nunit unit-testing automapper

0
推荐指数
1
解决办法
2577
查看次数

对象的Assert.AreEqual()失败

Assert.AreEqual()对于2个相同的对象失败.获取错误:: Assert.AreEqual失败.预期:.实际:.

以下是样本:

[TestMethod]
public void testMultiplication()
{ 
    Dollar five = new Dollar(5);
    Assert.AreEqual(new Dollar(10), five.times(2));
    Assert.AreEqual(new Dollar(15), five.times(3));
}

class Dollar
{
    private int amount;

    public Dollar(int amount)
    {
        this.amount = amount;
    }

    public Dollar times(int multiplier)
    {
        return new Dollar(amount * multiplier);
    }

    public bool equals(Object obj)
    {
        Dollar dollar = (Dollar) obj; 
        return amount == dollar.amount;
    }
}
Run Code Online (Sandbox Code Playgroud)

c# nunit

0
推荐指数
1
解决办法
493
查看次数

SpecFlow/NUnit/Selenium测试从错误的PWD运行

对于我正在开发的新项目,我的团队和我正在尝试使用ReSharper 10,NUnit,SpecFlow和Selenium设置一些功能测试.我们从一个已知的工作项目迁移了一堆旧代码,并使其构建没有问题.

但是,当我们运行代码时,我们不断收到以下错误:

OneTimeSetUp: System.IO.DirectoryNotFoundException : Could not find a part of the path 'C:\Users\Me\AppData\Local\SomeApp\App_Data\SomeApp.db'.

Exception doesn't have a stacktrace
Run Code Online (Sandbox Code Playgroud)

......这不对; 如果它找不到SomeApp.db文件,那应该是失败的C:\MyProjects\SomeApp\SomeApp.Web\App_Data\SomeApp.db!

这种情况下的相关代码在我们的TestSuite.cs类中:

[Binding]
public class TestSuite
{
    private string _currentPath;
    private string _localFile;
    private string _websiteBinPath;
    private string _websiteDataPath;

    // Stuff...

    [BeforeTestRun]
    public static void BeforeTestRun()
    {
        _currentPath = Directory.GetCurrentDirectory() + @"\";
        // Data:
        // <add key="TestWebsiteDataRelativePath" value="..\..\..\SomeApp.Web\App_Data\" />
        // <add key="TestWebsiteBinRelativePath" value="..\..\..\SomeApp.Web\bin\" />
        _websiteBinPath = Path.Combine(_currentPath, ConfigurationManager.AppSettings["TestWebsiteBinRelativePath"]);
        _websiteDataPath = Path.Combine(_currentPath, ConfigurationManager.AppSettings["TestWebsiteDataRelativePath"]);

        //removes the ../../../ …
Run Code Online (Sandbox Code Playgroud)

directory resharper nunit unit-testing

0
推荐指数
1
解决办法
606
查看次数