Solved

Testing

Posted on 2014-11-06
17
100 Views
Last Modified: 2014-11-09
Hi Anyone Can explain
How to
Create a test harness in a project
Using the test harness, demonstrate in debug mode, the object returning the correct information.

if any one show me with explain with good example ,i'll Highly appriciate.

Many Thanks
0
Comment
Question by:ukerandi
  • 10
  • 7
17 Comments
 
LVL 14

Expert Comment

by:Vel Eous
ID: 40427929
Unit testing is a large topic and there is a substantial amount of information available on the Internet, and in books regarding this topic;

http://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Getting-Started-with-Unit-Testing-Part-3 (includes links to parts 1 & 2)
http://www.rhyous.com/programming-development/csharp-unit-test-tutorial/
http://www.rhyous.com/2013/05/30/how-to-write-your-first-csharp-unit-test-with-visual-studio/

There are different frameworks available for creating unit tests (MSTest, NUnit, xUnit are common) and whilst they all attempt to achieve the same goal each has their own subtle differences in how they are used.  If you want an example provided which fits your scenario, a little more detail would be required such as which test framework you are using and what your test case(s) are.
0
 
LVL 10

Author Comment

by:ukerandi
ID: 40430363
Im using C# and Unit test Project its in the Visual Studio 2012 (New Project then select Test)

I create Following Methods I need to test this using  test harness
 public void View_NoOrders()
        {
        Open_Connection();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "select * from Orders  where OrderDate IS NULL";
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            Console.WriteLine("Firstname" + rdr["Firstname"].ToString());
               
       
        }

        rdr.Close();
        cmd.Connection.Close();


        Connection_Close();
       
        }

I need to  code above creates an instance of the above object, calls its method and displays the contents of the dataset.

Any comment Highly Appriciated
0
 
LVL 14

Expert Comment

by:Vel Eous
ID: 40430438
Something like the following then, however, I highly recommend based on what you've asked and the code you've provided that you read some of the documentation I provided links to previously.

[TestMethod]
public void View_NoOrders()
{
    // Arrange
    var rowCount = 0;
    var firstNames = new List<string>();
    Open_Connection();
    var cmd = new SqlCommand {Connection = con, CommandText = "select * from Orders  where OrderDate IS NULL"};

    // Act
    var rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        //Console.WriteLine("Firstname" + rdr["Firstname"]);
        firstNames.Add(rdr["Firstname"].ToString());
        rowCount++;
    }

    rdr.Close();
    cmd.Connection.Close();
    Connection_Close();

    // Assert
    Assert.Equal(1, rowCount); // replace 1 with however many rows you would expct return
    // Create a loop to assert each of the first names returned
}

Open in new window

0
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
LVL 10

Author Comment

by:ukerandi
ID: 40430474
Can you show me how to do that ,im not sure how to do loop with UNIT Test


   // Create a loop to assert each of the first names returned

Just wondring how to apply for  Assert.
 foreach (string value in firstNames)
            {
Assert.AreEqual(value,??
                //Console.WriteLine(value);
            }
0
 
LVL 10

Author Comment

by:ukerandi
ID: 40430481
Basically i need to call this method to Unit Test Project, i don't want to write whole code.

I need to know how to following code is combine with my ASSert.

Test.ConnectDB bc = new Test.ConnectDB();
            //PersonName target = new PersonName() { FirstName = "John", LastName = "Johnson" };
       
            Assert.AreEqual("BBBB111",bc.View_NoOrders())
// this generating Error
0
 
LVL 14

Expert Comment

by:Vel Eous
ID: 40430512
I don't know the entire working of your application so I cannot write the test for you, however, based on the information you provided me in the above comment it might look something like the following:

[TestMethod]
public void Assert_View_No_Orders_Equals_Something()
{
    // Arrange
    // This is the value you expect your Act method call to return
    // I have used an int as your View_NoOrders suggests it returns a count of some sort
    // If you are not testing int value, you need to change this accordingly.
    var expected = 12;
    var bc = new ConnectDB();

    // Act
    var actual = bc.View_NoOrders();

    // Assert
    Assert.Equal(expected, actual);
}

Open in new window

0
 
LVL 10

Author Comment

by:ukerandi
ID: 40430615
Hi
Im getting Error
var actual = bc.View_NoOrders(); <--- ERROR

Error is :
Error      1      Cannot assign void to an implicitly-typed local variable      C:\Users\ryan\Desktop\Test_Projects\UNIT\UnitTestProject1\UserTest.cs      74      17      UnitTestProject1
0
 
LVL 14

Expert Comment

by:Vel Eous
ID: 40430632
What is inside your View_NoOrders method?
0
 
LVL 10

Author Comment

by:ukerandi
ID: 40430647
public void View_NoOrders()
        {
            SqlConnection con = new SqlConnection();
       
        con.ConnectionString = "Data Source=RYAN123;Initial Catalog=RoDB;Integrated Security=True;"
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "select * from Orders  where OrderDate IS NULL";
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            Console.WriteLine("Firstname" + rdr["Firstname"].ToString());
               
       
        }

        rdr.Close();
        cmd.Connection.Close();


        Connection_Close();
       
        }
0
 
LVL 14

Expert Comment

by:Vel Eous
ID: 40430666
Your method doesn't return anything (void), you cannot test the return value of a method that doesn't return anything.

You need to alter your method to return something that can then best tested.

That said it doesn't seem worth while performing a test on this method as if the data in your database changes, it will potentially break your test and that has nothing to do with the functionality of your method which will not have changed.

Unit tests test functionality, not data.  They merely work with data.
0
 
LVL 10

Author Comment

by:ukerandi
ID: 40430678
Then How to do this
"
The objects interface should support one method, which returns a Dataset listing all of the customers who have not Orders any order

test harness in a project, write code that creates an instance of the above object, calls its method and displays the contents of the dataset"
0
 
LVL 14

Accepted Solution

by:
Vel Eous earned 500 total points
ID: 40430700
Something like the following perhaps?

using System;
using System.Data;
using System.Data.SqlClient;

public interface IInterface
{
    DataSet GetCustomersWithoutOrders();
}

public class ConcreteImplementation : IInterface
{
    public DataSet GetCustomersWithoutOrders()
    {
        var ds = new DataSet();

        var con = new SqlConnection();
        using (var conn = new SqlConnection("Data Source=RYAN123;Initial Catalog=RoDB;Integrated Security=True;"))
        {
            conn.Open();
            var cmd = new SqlCommand
            {
                Connection = con,
                CommandText = "select * from Orders  where OrderDate IS NULL"
            };
            var sqlAdapter = new SqlDataAdapter(cmd);
            sqlAdapter.Fill(ds);
        }
        return ds;
    }
}

[TestClass]
public class TestClass
{
    [TestMethod]
    public void ConcreteImplementation_GetCustomersWithoutOrders_HasData()
    {
        // Arrange
        var concreteImplementation = new ConcreteImplementation();

        // Act
        var dataSet = concreteImplementation.GetCustomersWithoutOrders();

        // Assert
        Console.WriteLine(dataSet.GetXml());
    }
}

Open in new window

0
 
LVL 10

Author Comment

by:ukerandi
ID: 40430730
Then How to use
Expected and Actual
Assert.Equals(
0
 
LVL 10

Author Comment

by:ukerandi
ID: 40430733
or   Assert.AreEqual("<Lastname>AAAA7</Lastname>", dataSet.GetXml());

its showing Test Failed
Any idea How to use this for invidual item serach
0
 
LVL 14

Expert Comment

by:Vel Eous
ID: 40430750
I would argue it is pointless performing an assert against the content of a dataset because as soon as the data in your database table changes, your assertion breaks.

The code snippet I provided previously also fulfils your second requirement, so why are you attempting to assert on the specifics of the content?
0
 
LVL 10

Author Closing Comment

by:ukerandi
ID: 40431019
Great , Expert Advice thanks
0
 
LVL 10

Author Comment

by:ukerandi
ID: 40431021
I'm very new to Unit test and Testing Software, so thats the why ask all questions to update my knowlwdge.Thx
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Adding bootstrap to only Content page and NOT master page 1 51
defining NULL or 0 10 44
Help with error in Query 2 31
Code works but breaks when I add one section 4 20
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question