C# unit test currency validation - c#

I need to write a unit test to test if the input is a valid currency value. I have tried several ways, but i don't think it's the correct way to test for currency value.
TEST CASE:
namespace validationUnitTest
{
// Validation rule for checking if the input is a valid currency value
public class CurrencyValidationRule: ValidationRule;
{
private static ValidationRule validationRule;
/// Singleton instance of this <see cref="ValidationRule"/>
public static ValidationRule Instance { get { return validationRule ?? (validationRule = new CurrencyValidationRule()); } }
// performs validation checks on a value
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value is double) return ValidationResult.ValidResult;
string stringValue = value as string;
double result;
return string.IsNullOrEmpty(stringValue) || double.TryParse(stringValue, NumberStyles.Currency, cultureInfo, out result) ? ValidationResult.ValidResult : new ValidationResult(false, "Value must be an number");
}
}
}
UNIT TEST:
namespace validationUnitTest.Tests
{
[TestClass()]
public class CurrencyValidationRuleTests
{
[TestMethod()]
public void ValidateTest()
{
var test = new CurrencyValidationRule();
var expected = new ValidationResult(true, true);
var actual = test.Validate("0", null);
Assert.AreEqual(expected.ErrorContent, actual.ErrorContent);
Assert.AreEqual(expected.IsValid, actual.Isvalid);
Assert.AreEqual(expected.GetHashCode(), actual.GetHashCode());
}
}
}
ANY idea on how I should start my unit test, or what I should be search for? I need some starting points. Any thing is greatly appreciate.

using System;
using System.Linq;
using Xunit;
using MonthlyStatements.Controllers;
using MonthlyStatements.Models;
using System.IO;
using System.Web.Mvc;
namespace UnitTestProject1
{
public class UnitTest1
{
[Theory]
[InlineData(10.20, "System.Double")]
[InlineData(0, "System.Double")]
public void checkValidation(double amt, string ExpectedResult)
{
//Arrange
string actualResult = "";
//Act
//double doubleAmt = double.Parse(amt.ToString());
actualResult = amt.GetType().ToString();
//Assert
Assert.Equal(ExpectedResult, actualResult);
}
}
}

use Xunit instead of nUnit , before start developing we have to conside following
Rules : 1) we test only public methods 2) we have to know input
parameter and out Put parameter like expected Result and Actual result
in above code you used 3 assert it is not correct way,
here you can check data Type of actual result, use xunit [InlineData()] so dont need to repeat code .

Related

Setup Method with object type parameter using MOQ

I have an interface
public interface IProgramer
{
bool ReturnStatus(Program prg,string filepath);
}
Class
public class Programer :IProgramer
{
public bool ReturnStatus(Program prg,string filepath)
{
// logic
return status
}
}
Unit Testcase
public void StartOperationTest()
{
string dummyfilepath = "C://Users//x//";
Program dummyprgObj = new Program
{
Name = "x",
Rollno = 1,
};
var mock = new Mock<IProgramer>();
mock.Setup(x => x.ReturnStatus(dummyprgObj, dummyfilepath)).Returns(true);
}
setup method is always giving false.
Can someone please tell me what is wrong here?
Try using mock.SetupGet() instead of 'setup' you are using.
and also one observation, the class 'Programer' should implement interface 'IProgramer'

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.

How do I do unit tests in Visual Studio 2015

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.

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.

Rhino Mocks doesnt mock a method

Im trying to mock a method, it compiles without errors, but smth strange happens when i run a test. Actually method doesnt mock or maybe I dont understand smth...(
Here's a code:
public class Robot
{ ....
public virtual bool range(IObs ob, double range)
{
double dist = ob.distanceSq(this);
if (dist < range)
return true;
else
return false;
}
}
...
public interface IObs
{
double distanceSq(Robot r);
}
...
Unit Test:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
MockRepository mocks = new MockRepository();
IObs obstacleMock = mocks.CreateMock<IObs>();
Robot r = new Robot();
Expect.Call(obstacleMock.distanceSq(r)).IgnoreArguments()
.Constraints(Is.Anything())
.Return(5.5);
Assert.IsTrue(r.range(obstacleMock, 0.5));
}
}
I mock distanceSq().
When I debug my test, i see that ob.distanceSq(this) is 0.0. (not 1.5).
What's wrong?
Your code does not actually use mock you created - as you can change Obstacle to IObjs as argument of range and than pass mock instead of new instance of Obstacle:
public virtual bool range(IObjs ob, double range)....
class Obstacle : IObjs ...
Assert.IsTrue(r.range(obstacleMock, 0.5));
I would recommend that you upgrade your RinoMocks version to 3.6 and use the new syntax.
Additionally if you are using a mock for IObs, you may as well verify that the distanceSq method is called.
I have left the verification of the parameters in the distanceSq method out of this code, but you could ensure that the correct Robot instance is passed in.
The unit test will still fail however, as 5.5 is greater than 0.5
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
namespace Rhino
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var r = new Robot();
var obstacleMock = MockRepository.GenerateMock<IObs>();
obstacleMock.Expect(x => x.ditanceSq(Arg<Robot>.Is.Anything)).Return(5.5);
//use this line to ensure correct Robot is used as parameter
//obstacleMock.Expect(x => x.ditanceSq(Arg<Robot>.Is.Equal(r))).Return(5.5);
var result = r.range(obstacleMock, 0.5);
obstacleMock.VerifyAllExpectations();
Assert.IsTrue(result);
}
}
public class Robot
{
public virtual bool range(IObs ob, double range)
{
return ob.ditanceSq(this) < range;
}
}
public interface IObs
{
double ditanceSq(Robot r);
}
}

Categories

Resources