Perform unit test in Eclipse or Visual Studio

1

Having the following function:

public int Suma (int numero1, int numero2){
return numero1+numero2;
}

Be in Java or C# .

Is there a way to test this function without having to invoke it in the MAIN?

So if I have several functions or methods of the classes in my project, I have some way to test them one by one (hardcode the parameters that I want), without having to instantiate the classes or call the functions in the body main (main)?

    
asked by Oren Diaz 07.03.2018 в 19:12
source

1 answer

3
  

To do so in Visual Studio 2013 or higher

In previous versions I do not know if it's the same process, but not It must be very different.

1.- You must add a Test Project, on your solution, do the following:

Right click > Add New Project > Visual C # > Testing > Unit Test Project

2.- You must import the references to your Unit Test Project (they can be other projects of your same solution or already compiled dlls) that you want to test.

3.- The Test Project creates a class similar to this one by default.

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {

    }
}

4.- Suppose you have a class called Operaciones.cs in another project and you import it into the Test Project to test its methods.

public class Operaciones
{
    public int Suma(int numero1, int numero2)
    {
        return numero1 + numero2;
    }
}

5.- This way you would make a Test of the Sum method in your Test Project.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DemoUtils; /*Es la referencia del proyecto que contiene la clase 
Operaciones*/

namespace UnitTestProject1
{
  [TestClass]
  public class UnitTest1
  {
      [TestMethod]
      public void TestMethod1()
      {
        Operaciones operacion = new Operaciones();

        Assert.AreEqual(10, operacion.Suma(5, 5));        
      }
   }
}

In the previous code, you can specify a class of Operations, and with Assert.AreEqual you indicate that the value of the first parameter must be Equal to the result that you will obtain from your Sum method > for the test to be completed.

  

There are other methods of Assert that you can go   testing according to your requirements.

6.- To start your unit test, right click on TestMethod1 and click on Run tests or with the shortcut Ctrl + R, T. p>

I hope you find it useful.

    
answered by 07.03.2018 / 22:47
source