logo
Tags down

shadow

Should unit tests tests the functionality of a method?


By : Jeevanandam K
Date : October 17 2020, 06:10 AM
it helps some times I am writing unit tests but the part that confuses me most is whether it should test the functionality or not? ,
For example, if there is a method which does two things
code :
public class MySpaceManager()
{
  private readonly IFileManager _fileManager;
  public MySpaceManager(IFileManager fileManager)
  {
    _fileManager = fileManager;
  }


  public bool TryDeleteAllFiles1(logicalDirectory)
  {
    var files = _fileManager.GetFiles(logicalDirectory);
    var result = true;
    foreach(var file in files)
      result = result && _fileManager.Delete(file);

    return result;
  }

  // or maybe

  public bool TryDeleteAllFiles2(logicalDirectory)
  {
    var files = _fileManager.GetFiles(logicalDirectory);
    foreach(var file in files)
      _fileManager.Delete(file);

    var result = _fileManager.GetFiles(logicalDirectory).Count() == 0;
    return result;
  }

}
public class MySpaceManagerTests
{
  // First simple, best good path for code
  public void TryDeleteAllFiles2_WithEmptyPath_ThrowsNoException()
  {
    /// ** ASSIGN **

    // I'm using NSubstitute here just for an example
    // could use Moq or RhinoMocks, whatever doesn't  
    // really matter in this instance
    // the important part is that we do NOT test dependencies
    // the class relies on.
    var fileManager = Substitute.For<IFileManager>();
    fileManager
      .GetFiles(Args.Any<string>())
      .Returns(new List<IFile>());

    var mySpaceManager = new MySpaceManager(fileManager);

    // ** ACT && ASSERT**

    // we know that the argument doesn't matter so we don't need it to be
    // anything at all, we just want to make sure that it runs to completion
    Asser.DoesNotThrow(() => mySpaceManager.TryDeleteAllFiles2(string.Empty);
  }

  // This looks VERY similar to the first test but
  // because the assert is different we need to write a different
  // test.  Each test should only really assert the name of the test
  // as it makes it easier to debug and fix it when it only tests
  // one thing.
  public void TryDeleteAllFiles2_WithEmptyPath_CallsFileManagerGetFiles()
  {
    /// ** ASSIGN **
    var fileManager = Substitute.For<IFileManager>();
    fileManager
      .GetFiles(Args.Any<string>())
      .Returns(new List<IFile>());

    var mySpaceManager = new MySpaceManager(fileManager);

    // ** ACT **
    mySpaceManager.TryDeleteAllFiles2(string.Empty)

    // ** ASSERT **
    Assert.DoesNotThrow(fileManager.Received().GetFiles());
  }

  public void TryDeleteAllFiles2_With0Files_DoesNotCallDeleteFile
  {
    /// ** ASSIGN **
    var fileManager = Substitute.For<IFileManager>();
    fileManager
      .GetFiles(Args.Any<string>())
      .Returns(new List<IFile> { Substitute.For<IFile>(); });

    var mySpaceManager = new MySpaceManager(fileManager);

    // ** ACT **
    mySpaceManager.TryDeleteAllFiles2(string.Empty)

    // ** ASSERT **
    Assert.DoesNotThrow(fileManager.DidNotReceive().GetFiles());
  }

  public void TryDeleteAllFiles2_With1File_CallsFileManagerDeleteFile
  {
    // etc
  }

  public void TryDeleteAllFiles2_With1FileDeleted_ReturnsTrue()
  {
    /// ** ASSIGN **
    var fileManager = Substitute.For<IFileManager>();
    fileManager
      .GetFiles(Args.Any<string>())
      .Returns(new List<IFile> { Substitute.For<IFile>(); }, 
        new list<IFile>());

    var mySpaceManager = new MySpaceManager(fileManager);

    // ** ACT **
    var actual = mySpaceManager.TryDeleteAllFiles2(string.Empty)

    // ** ASSERT **
    Assert.That(actual, Is.True);
  }

  public void TryDeleteAllFiles2_With1FileNotDeleted_ReturnsFalse()
  {
    /// ** ASSIGN **
    var fileManager = Substitute.For<IFileManager>();
    fileManager
      .GetFiles(Args.Any<string>())
      .Returns(new List<IFile> { Substitute.For<IFile>(); }, 
        new List<IFile> { Substitute.For<IFile>(); });

    var mySpaceManager = new MySpaceManager(fileManager);

    // ** ACT **
    var actual = mySpaceManager.TryDeleteAllFiles2(string.Empty)

    // ** ASSERT **
    Assert.That(actual, Is.False);
  }
}


Share : facebook icon twitter icon

What are unit tests, integration tests, smoke tests, and regression tests?


By : Halvat lennot
Date : March 29 2020, 07:55 AM
I wish this helpful for you
Unit test: Specify and test one point of the contract of single method of a class. This should have a very narrow and well defined scope. Complex dependencies and interactions to the outside world are stubbed or mocked.

Should positive and negative unit tests for one method have individual tests?


By : Donggeun Lee
Date : March 29 2020, 07:55 AM
hope this fix your issue You should create seperate test cases for each case. This will give you confidence that any future code that calls this method will work, also if you refactor you can see exactly which test fails, instead of just seeing 1test fail and have no idea why.

What value would I get from integration tests when I already write unit tests and functional tests


By : Wayne Wei Heng
Date : March 29 2020, 07:55 AM
I hope this helps . The question is "What would be get from writing integration tests? What would be the benefits of the extra time spent writing these tests?"
Your integration tests will ensure that your components work together with cross cutting concerns such as web services, db, session etc. You only need only few integration tests - As @bagheera's comment on TestPyramid. Be aware how you write integration tests because if you go overboard, it can really slow to run all of them, and harder to work with. When you compare them to Unit Tests, you don't get much benefit of writing them.

Using Unit Tests which are not independent to create Use Case tests (Scenario tests)


By : pmb12
Date : March 29 2020, 07:55 AM
may help you . I think it's useful to draw a distinction and use tools that are best suited for the job. What it looks like you are describing is specification testing, which is the realm of Behavior Driven Design (BDD).
A short list of C# BDD test suites include:

Can pom.xml be set up to run testNG(UI perf. tests) tests and jUnit(unit tests) tests separately, from command line?


By : user2364643
Date : March 29 2020, 07:55 AM
Hope that helps Yes you can do that. You need to make two separate testng files with different names and add unit tests in one testng and performance tests in other and you can parameterised it from the pom.xml like:
code :
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20.1</version>
    <configuration>
        <suiteXmlFiles>
            <suiteXmlFile>${suiteXmlFile}</suiteXmlFile>
        </suiteXmlFiles>
    </configuration>
</plugin>
Related Posts Related Posts :
  • Submit Button is not working In Razor asp.net mvc
  • While loop multiple condition check with single variable
  • Inside a catch clause, how can I see an exception without a name
  • How I can use Certificate.pfx for windows exe build
  • I'm trying to detect that SQL Server Compact Edition is installed in a system or not
  • UWP Replace MainView with FullScreen Frame
  • How do I display the data of the "current user"?
  • AVX2 SIMD XOR not yielding performance improvements in .NET
  • Algorithm to find the closest time
  • Xamarin Form - How To store an image in PDF or JPEG Format in UWP
  • ModelState error: The value 'null' is not valid for nullable field
  • Pre Increment of an operator
  • MSTest Asserts fail with null reference
  • Getting random numbers after a simple math problem. Might be a local variable thing
  • Convert HTML to PDF using HTML Renderer using C# and XML to Pdf
  • Conversion failed when converting varchar value to datatype bit
  • How to edit an XML file in Streamingassets from my hololens
  • Naming a DispatcherTimer based on a string from another method?
  • How to call the default browser in the Hololens app
  • How do I close an IF statement if there is no more code to be executed with 'else'?
  • Unity3D: Is there a easy way to give a min/max to a value in the inspector?
  • The type or namespace name 'ICloudRecoEventHandler' could not be found
  • When compiling C# expression trees into methods, is it possible to access "this"?
  • Sort an array of strings in ascending order in C#
  • How detect is a method in a C# class is implementing a method from an interface?
  • How to parse a timespan in order to add it to a datetime?
  • Changing code from if-statement to switch-statement in C#
  • Linq GroupBy Clause not including items with zero count
  • How to determine the highest value in a list of properties
  • C# Custom Json.NET List serialization
  • Session Variable is null after using RedirectToAction
  • How to manipulate c# code programatically In .Net Core?
  • Modifying Windows System sounds
  • Is there a way to convert this powershell script to C#
  • Lists will show null even though assigned in constructor
  • Any way to have a `using` block that doesn't define a scope block?
  • How do I get a result from this mocked service?
  • async await losing response in c#
  • How can I pause an execution without using Thread.Sleep()
  • How to Stop In Azure Ad Authentication Sign Out ask for Which account do you want to sign out of?
  • Use operators with and without space in c#
  • Remove duplicates from comma separated list
  • Use a String variable as argument from if sentence
  • unity how to avoid scaling heritage when parenting?
  • Is there a way to do nested model binding with the [FromBody] attribute?
  • How to insert dynamic query into table using c#
  • Why Unit Testing Assert.AreEqual() method does NOT pick up my own Equals() method in the customized class
  • Unity Error: Feature 'out variable declaration'
  • What happens if my C# switch expression is non-exhaustive?
  • How Can I Select an ItemTemplate Based on a Value?
  • EF Class table name and column have same name
  • Substring issues - input string was not in a correct format
  • C# Asynchronously read data from a redirected StandardOutput
  • The code after await operation is not executing
  • Image FILL logic such as "Stretch.Uniform" of WPF
  • Why am I allowed to declare a variable with the same name?
  • Simplest way to display colored 3D boxes in winforms
  • Conventions on having both an API and MVC project in .NET Core solution
  • File upload .NET Core 'IFormFile' does not contain a definition for 'CopyToAsync' and no extension method
  • Deserialize only valid objects by ignoring errors
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk