How do I do unit tests in Visual Studio 2015 - c#

I have like below.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Syncfusion.Gitlab
{
public class Branches
{
public void CreateBranch(List<string> projectName, string sourceBranch, string destinationBranch)
{
}
public void CreateTag(List<string> projectName, string sourceBranch,string tagname)
{
}
public static List<string> GetBranchList(string projectId)
{
}
public static List<ProjectData> GetProjectList()
{
}
}
public class ExcelOperation
{
public void GenerateExcel(List<ProjectDetails> finalExcelData, List<string>projectUrl,List<string>tagsorBranchUrl)
{
}
}
}
I can able to test the method and got the positive output. But I do not know how to test these two method public static List<string> GetBranchList(string projectId), public static List<ProjectData> GetProjectList()
My sample test code is below. Below method is successfully passed in NUnit test.
[TestMethod]
public void CreateTags()
{
List<string> project = new List<string>();
project.Add("test1");
string sourceBranch = "master";
string tagsName = "v1.0.0";
branch.CreateTag(project, sourceBranch, tagsName);
}
How can I test the that two methods?
Update:
I can get the answer with the help of first answer. But Now I have anouther doubt.
How could I test for wrong input? I mean I know that the input I was given Is wrong but I need the green tick mark for that testing. That means the input given is wrong so the output also wrong therfore the testing is right.
In my below image. I need public void GetBranchListforWrongInput() also green tick mark.
How could I do it?

Unit testing static method is pretty much as same as testing non-static methods. It might get complex based on what logic you have in the static method.
But simplest way for your case would be as following.
[TestMethod]
public void TestGetBranchList()
{
string projectId = "someProjectId";
var result = Branches.GetBranchList(projectId);
//Assert if result has expected result.
}
[TestMethod]
public void TestGetProjectList()
{
var result = Branches.GetProjectList();
//Assert if result has expected result.
}
[TestMethod]
public void TestCreateBranch()
{
//Prepare TestData
List<string> projectName = new List<string> {"someProject"};
string sourceBranch = "sourceBranch"
string destinationBranch = "destBranch";
Branches branchesObj = new Branches();
// Call method by passing the test data.
branchesObj.CreateBranch(projectName, sourceBranch, destinationBranch);
}
This should help you resolve your issue.

Related

How to test function that has objects as parameters in XUnit?

I have a simple function that takes Client and Supplier data and then calculates tax based on where they live and other information:
static int CountTax(Supplier tiek, Client kl, bool same_country)
{
if ( !tiek.is_PVM_payer)
return 0;
else
{
if (!kl.EU)
return 0;
else
{
if (same_country)
return kl.x;
else
{
if (kl.is_PVM_payer)
return 0;
else
return kl.x;
}
}
}
}
Now I am required to write tests for this function. It is the first time I am encountering tests. I am using XUnit testing. And my test class looks like this:
using System;
using Xunit;
namespace CountTax_tests
{
public class UnitTest1
{
[Theory]
[InlineData(typeof(Client))]
public void Tax_is_0()
{
// arrange
int expectedVal = 0;
int actualVal;
/// act
actualVal = MyProgram.MyprogramCode.CountTax(supplier, client, same_country);
// assert
Assert.Equal(expectedVal, actualVal);
}
[Fact]
public void PVM_is_x()
{
int expectedVal = x;
int actualVal;
actualVal = MyProgram.MyprogramCode.CountTax(supplier, client, same_country);
Assert.Equal(expectedVal, actualVal);
}
}
}
But how do I pass my Client and Supplier parameters to that test? Please help me and lead on a path because I am completely new and nothing is clear to me even after many tutorials...
Maybe I have to use [Theory]? Or maybe [Fact]? Or maybe it is impossible to pass classes as parameters?
Also, [InlineData(typeof(Client))] is being underlined in red and is not working.

Unit Testing SQLite Repository generating No Such Table Error

I have recently built a quiz application for Xamarin.Android, and want to dome some Unit Testing on the shared library.
I am using a repository pattern with the following files.
SQLiteMyAppRepository.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SQLite;
namespace MyApp.DataLayer
{
public class MyAppRepository : IMyAppRepository
{
public static string DatabaseName = "MyApp.sqlite";
private SQLiteConnection _dbConnection;
public MyAppRepository()
{
string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string dbFilePath = Path.Combine(docFolder, DatabaseName);
_dbConnection = new SQLiteConnection(dbFilePath);
}
I have then created a new project to test some of these elements.
The primary issue I am having, is that when I try and run the test, I am getting the following exception:
MyApp.Tests.RepositoryTests.AddQuestion threw
exception:
SQLite.SQLiteException: no such table: Questions
I have been messing about with it for a few hours now and can't seem to find what is wrong, any help would be appreciated. I thought Mocking the repository would get around any issues like this.
The problem here is that you are trying to use a real database in the context of unit tests. One possible solution could be to introduce an additional level of abstraction and separate repository from context(database). This could enable you to properly mock dependencies, e.g.
public interface IMyAppContext
{
IList<Question> GetAllQuestions();
int AddQuestion(Question question);
int UpdateQuestion(Question question);
int DeleteQuestion(Question question);
}
where implementation could be something like this:
public class MyAppContext : IMyAppContext
{
private readonly string _databaseName = "MyApp.sqlite";
private readonly SQLiteConnection _dbConnection;
public MyAppContext()
{
string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string dbFilePath = Path.Combine(docFolder, DatabaseName);
_dbConnection = new SQLiteConnection(dbFilePath);
}
public int AddQuestion(Question question)
{
return _dbConnection.Insert(question);
}
...
}
then inject this one to the repository...
public class MyAppRepository : IMyAppRepository
{
private readonly IMyAppContext _context;
public MyAppRepository(IMyAppContext context)
{
_context = context;
}
public int AddQuestion(Question question)
{
return _context.Insert(question);
}
...
}
Now, after you have done this setup of the unit test should be for example,
[TestMethod]
public void AddQuestion()
{
// Arrange
var contextMock = new Mock<IMyAppContext>();
contextMock.Setup(r => r.AddQuestion(It.IsAny<Question>())).Returns(1);
var sut = new SqLiteAbcdRepository(contextMock.Object);
// Act
var id = sut.AddQuestion(new Question());
// Assert
Assert.AreEqual(1, id);
}

ML.NET to predict New York taxi fares - Program does not contain a static 'Main' method suitable for an entry point [duplicate]

This question already has answers here:
Can't specify the 'async' modifier on the 'Main' method of a console app
(20 answers)
Closed 4 years ago.
I was trying to do the example of ML.net to predict New York taxi fares, but when I finished the tutorial had the message: Program does not contain a static 'Main' method suitable for an entry point
Here the code that I did:
Class Program.cs
using System;
using System.IO;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Models;
using Microsoft.ML.Trainers;
using Microsoft.ML.Transforms;
using System.Threading.Tasks;
namespace TaxiFarePrediction2
{
public class Program
{
static readonly string _datapath = Path.Combine(Environment.CurrentDirectory, "Data", "taxi-fare-train.csv");
static readonly string _testdatapath = Path.Combine(Environment.CurrentDirectory, "Data", "taxi-fare-test.csv");
static readonly string _modelpath = Path.Combine(Environment.CurrentDirectory, "Data", "Model.zip");
static async Task Main(string[] args)
{
PredictionModel<TaxiTrip, TaxiTripFarePrediction> model = await Train();
Evaluate(model);
TaxiTripFarePrediction prediction = model.Predict(TestTrips.Trip1);
Console.WriteLine("Predicted fare: {0}, actual fare: 29.5", prediction.FareAmount);
}
public static async Task<PredictionModel<TaxiTrip, TaxiTripFarePrediction>> Train()
{
var pipeline = new LearningPipeline
{
new TextLoader(_datapath).CreateFrom<TaxiTrip>(useHeader: true, separator: ','),
new ColumnCopier(("FareAmount", "Label")),
new CategoricalOneHotVectorizer(
"VendorId",
"RateCode",
"PaymentType"),
new ColumnConcatenator(
"Features",
"VendorId",
"RateCode",
"PassengerCount",
"TripDistance",
"PaymentType"),
new FastTreeRegressor()
};
PredictionModel<TaxiTrip, TaxiTripFarePrediction> model = pipeline.Train<TaxiTrip, TaxiTripFarePrediction>();
await model.WriteAsync(_modelpath);
return model;
}
private static void Evaluate(PredictionModel<TaxiTrip, TaxiTripFarePrediction> model)
{
var testData = new TextLoader(_testdatapath).CreateFrom<TaxiTrip>(useHeader: true, separator: ',');
var evaluator = new RegressionEvaluator();
RegressionMetrics metrics = evaluator.Evaluate(model, testData);
Console.WriteLine($"Rms = {metrics.Rms}");
Console.WriteLine($"RSquared = {metrics.RSquared}");
}
}
}
class TaxiTrip.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ML.Runtime.Api;
namespace TaxiFarePrediction2
{
public class TaxiTrip
{
[Column("0")]
public string VendorId;
[Column("1")]
public string RateCode;
[Column("2")]
public float PassengerCount;
[Column("3")]
public float TripTime;
[Column("4")]
public float TripDistance;
[Column("5")]
public string PaymentType;
[Column("6")]
public float FareAmount;
}
public class TaxiTripFarePrediction
{
[ColumnName("Score")]
public float FareAmount;
}
}
class TestTrips.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ML.Runtime.Api;
namespace TaxiFarePrediction2
{
public class TaxiTrip
{
[Column("0")]
public string VendorId;
[Column("1")]
public string RateCode;
[Column("2")]
public float PassengerCount;
[Column("3")]
public float TripTime;
[Column("4")]
public float TripDistance;
[Column("5")]
public string PaymentType;
[Column("6")]
public float FareAmount;
}
public class TaxiTripFarePrediction
{
[ColumnName("Score")]
public float FareAmount;
}
}
The tutorial is in : https://learn.microsoft.com/en-us/dotnet/machine-learning/tutorials/taxi-fare
please help me to do this example.
Main method can not support asycn before c# 7.1, You can start main once and than create tasks in main method that can be async if you are using earlier versions.
You can writesomething mentioned by Chris Moschini
class Program
{
static void Main(string[] args)
{
Task.Run(async () =>
{
// Do any async anything you need here without worry
}).GetAwaiter().GetResult();
}
The link you posted clearly mention about c# version specified ...
Because the async Main method is the feature added in C# 7.1 and the default language version of the project is C# 7.0, you need to change the language vers
ion to C# 7.1 or higher. To do that, right-click the project node in Solution Explorer and select Properties. Select the Build tab and select the Advanced button. In the dropdown, select C# 7.1 (or a higher version). Select the OK button.
A good read on main with async

Unit testing class

I'm doing unit testing with a class library and I'm stuck on how to test the method that need to test scenarios like check if a password with less than 8 characters cannot be accepted, check if a password with 8 or more characters can be accepted and check if a password with space in the front cannot be accepted.
The code below is from the class library.
public class PasswordChecker
{
public bool CheckPassword(string pwd)
{
if (pwd.Length >= 8 && !pwd.StartsWith(""))
{
return true;
}
else
{
return false;
}
}
}
The code below is from the testing project.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using 12kiajunPA03;
namespace PasswordCheckerTest
{
[TestClass]
public class PasswordCheckerTest
{
[TestMethod]
public void Checkpassword()
{
string pwd = "1234qa1";
Checkpassword password = new Checkpassword("John", pwd);
try
{
}
catch
{
}
}
}
}
I imagine it would look something like this:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using 12kiajunPA03;
namespace PasswordCheckerTest
{
[TestClass]
public class PasswordCheckerTest
{
[TestMethod]
public void Checkpassword8CharsLong()
{
string validPassword = "12345678";
string invalidPassword = "abc";
PasswordChecker checker = new PasswordChecker();
Assert.IsTrue(checker.CheckPassword(validPassword));
Assert.IsFalse(checker.CheckPassword(invalidPassword));
}
}
}
Using the same idea, you could write additional tests that check for other criteria that the passwords must meet.

C# NUnit using TestCaseSource results in NullPointer

I have the following class which is a TestFixture which has one test and a TestCaseSource that produces my TestCases. My test case actually contain both the actual result and the expected result which is wrapped in an Object called TestCaseEntity
namespace SomeNamespace
{
[TestFixture]
public class MyTest
{
static Client client;
static List<string> userIds = new List<string>();
[TestFixtureSetUp]
public void Init()
{
// Set up a client
client = new Client("server address"); // a HTTP client
// populate a List of userIds from a local text test file
userIds.Add(GetAllIdsFromTxtFile());
}
[Test, TestCaseSource(typeof(MyTestCaseEntityFactory), "MyTestCases")]
public void CheckExpectations(TestCaseEntity testCaseEntity)
{
if (!testCaseEntity.IsIdentical)
{
Log.Error("Log some shit");
Assert.Fail("fail assertions");
}
}
public class MyTestCaseEntityFactory
{
public static IEnumerable<TestCaseEntity> MyTestCases
{
get
{
foreach (string id in userIds)
{
// use the client and get the results, construct the new TestCaseEntity(...) and return;
yield return new TestCaseEntity("actualValue", "expectedValue resulting from the server call");
}
}
}
}
}
}
When I run my Test, I get the following error which is unfortunately not very helpful!
System.NullReferenceException : Object reference not set to an instance of an object.
Any suggestions on what I might have done wrong?
You foreach over allSalesDEDealIds but you seem to have not included it in your code example. It might be that this is the NullRefExceptionin your code?

Categories

Resources