I need to write a simple method that receives a parameter (e.g. a string) and does smth. Usually I'd end up with two tests. The first one would be a guard clause. The second would validate the expected behavior (for simplicity, the method shouldn't fail):
[Fact]
public void DoSmth_WithNull_Throws()
{
var sut = new Sut();
Assert.Throws<ArgumentNullException>(() =>
sut.DoSmth(null));
}
[Fact]
public void DoSmth_WithValidString_DoesNotThrow()
{
var s = "123";
var sut = new Sut();
sut.DoSmth(s); // does not throw
}
public class Sut
{
public void DoSmth(string s)
{
if (s == null)
throw new ArgumentNullException();
// do smth important here
}
}
When I try to utilize the FsCheck [Property] attribute to generate random data, null and numerous other random values are passed to the test which at some point causes NRE:
[Property]
public void DoSmth_WithValidString_DoesNotThrow(string s)
{
var sut = new Sut();
sut.DoSmth(s); // throws ArgumentNullException after 'x' tests
}
I realize that this is the entire idea of FsCheck to generate numerous random data to cover different cases which is definitely great.
Is there any elegant way to configure the [Property] attribute to exclude undesired values? (In this particular test that's null).
FsCheck has some built-in types that can be used to signal specific behaviour, like, for example, that reference type values shouldn't be null. One of these is NonNull<'a>. If you ask for one of these, instead of asking for a raw string, you'll get no nulls.
In F#, you'd be able to destructure it as a function argument:
[<Property>]
let DoSmth_WithValidString_DoesNotThrow (NonNull s) = // s is already a string here...
let sut = Sut ()
sut.DoSmth s // Use your favourite assertion library here...
}
I think that in C#, it ought to look something like this, but I haven't tried:
[Property]
public void DoSmth_WithValidString_DoesNotThrow(NonNull<string> s)
{
var sut = new Sut();
sut.DoSmth(s.Get); // throws ArgumentNullException after 'x' tests
}
Related
I have a set of domain object, deriving from a base, where I've overridden Equals, IEquatable<T>.Equals and equality operators. I've successfully used Contains, but now I am trying to use Distinct differently. Here's look at a sample code:
var a = new Test { Id = 1 };
var a2 = new Test { Id = 1 };
var list = new List<Test> { a, a2 };
var distinct = list.Distinct().ToList(); // both objects, Equal implementations not called
var containsA = list.Contains(a); // true, Equal implementations called
var containsA2 = list.Contains(a); // true
var containsNewObjectWithSameId = list.Contains(new Test { Id = 1 }); // true
public class Test : IEquatable<Test>
{
public int Id { get; init; }
public bool Equals(Test other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (this.GetType() != other.GetType())
return false;
return this.Id == other.Id;
}
public override int GetHashCode() => base.GetHashCode + this.Id;
}
Contains finds matches, but Distinct is feeling very inclusive and keeps them both. From MS docs:
The first search does not specify any equality comparer, which means FindFirst uses
EqualityComparer.Default to determine equality of boxes. That in turn uses the implementation
of the IEquatable.Equals method in the Box class.
What am I missing?
Thanks #JonSkeet for your insight in the comments.
The problem in this case is the way I wrote my GetHashCode method. It has nothing to do with LINQ, as I originally thought.
Explanation
GetHashCode has to be identical for objects that compare equally. In my case - since the base implementation of object.Equals only checks for reference equality and I am comparing two separate objects - a and b, their base.GetHashCode would result in different values, which in turn would render those two objects as not equal.
Solution
In this case, simply returning the Id value is enough as is shown in MS docs:
One of the simplest ways to compute a hash code for a numeric value that has the same or a smaller range than the Int32 type is to simply return that value.
So changing the above code sample like this:
public override int GetHashCode() => this.Id;
would solve the issue. Please keep in mind that if the value of Id is not unique, this will cause ill behavior. In such cases you'll need another property to check and you will have to compose GetHashCode from ALL those properties. For further info refer to MS docs
I am migrating my prototype from a listener to a visitor pattern. In the prototype, I have a grammar fragment like this:
thingList: thing+ ;
thing
: A aSpec # aRule
| B bSpec # bRule
;
Moving to a visitor pattern, I am not sure how I write visitThingList. Every visitor returns a specializes subclass of "Node", and I would love somehow when to be able to write something like this, say a "thingList" cares about the first thing in the list some how ...
visitThingList(cx: ThingListContext): ast.ThingList {
...
const firstThing = super.visit(cx.thing(0));
The problem with this is in typing. Each visit returns a specialized type which is a subclass of ast.Node. Because I am using super.visit, the return value will be the base class
of my node tree. However, I know because I am looking at the grammar
and because I wrote both vistARule and visitBRule that the result of the visit will be of type ast.Thing.
So we make visitThingList express it's expectation with cast ...
visitThingList(cx: ThingListContext): ast.ThingList {
const firstThing = super.visit(cx.thing(0));
if (!firstThing instanceof ast.Thing) {
throw "no matching visitor for thing";
}
// firstThing is now known to be of type ast.Thing
...
In much of my translator, type problems with ast Nodes are a compile time issue, I fix them in my editor. In this case, I am producing a more fragile walk, which will only reveal the fragility at runtime and then only with certain inputs.
I think I could change my grammar, to make it possible to encode the
type expectations of vistThingList() by creating a vistThing() entry point
thingList: thing+ ;
thing: aRule | bRule;
aRule: A aSpec;
bRule: B bSpec;
With vistThing() typed to match the expectation:
visitThing(cx: ThingContext): ast.Thing { }
visitThingList(cx: ThingListContext) {
const firstThing: ast.Thing = this.visitThing(cx.thing(0));
Now visitThingList can call this.visitThing() and the type enforcement of making sure all rules that a thing matches return ast.Thing belongs to visitThing(). If I do create a new rule for thing, the compiler will force me to change the return type of visitThing() and if I make it return something which is NOT a thing, visitThingList() will show type errors.
This also seems wrong though, because I don't feel like I should have to change my grammar in order to visit it.
I am new to ANTLR and wondering if there is a better pattern or approach to this.
When I was using the listener pattern, I wrote something like:
enterThing(cx: ThingContext) { }
enterARule(cx : ARuleContext) { }
enterBRule(cx : BRuleContext) { }
Not quite: for a labeled rule like thing, the listener will not contain enterThing(...) and exitThing(...) methods. Only the enter... and exit... methods for the labels aSpec and bSpec will be created.
How would I write the visitor walk without changing the grammar?
I don't understand why you need to change the grammar. When you keep the grammar like you mentioned:
thingList: thing+ ;
thing
: A aSpec # aRule
| B bSpec # bRule
;
then the following visitor could be used (again, there is no visitThing(...) method!):
public class TestVisitor extends TBaseVisitor<Object> {
#Override
public Object visitThingList(TParser.ThingListContext ctx) {
...
}
#Override
public Object visitARule(TParser.ARuleContext ctx) {
...
}
#Override
public Object visitBRule(TParser.BRuleContext ctx) {
...
}
#Override
public Object visitASpec(TParser.ASpecContext ctx) {
...
}
#Override
public Object visitBSpec(TParser.BSpecContext ctx) {
...
}
}
EDIT
I do not know how, as i iterate over that, to call the correct visitor for each element
You don't need to know. You can simply call the visitor's (super) visit(...) method and the correct method will be invoked:
class TestVisitor extends TBaseVisitor<Object> {
#Override
public Object visitThingList(TParser.ThingListContext ctx) {
for (TParser.ThingContext child : ctx.thing()) {
super.visit(child);
}
return null;
}
...
}
And you don't even need to implement all methods. The ones you don't implement, will have a default visitChildren(ctx) in them, causing (as the name suggests) all child nodes under them being traversed.
In your case, the following visitor will already cause the visitASpec and visitBSpec being invoked:
class TestVisitor extends TBaseVisitor<Object> {
#Override
public Object visitASpec(TParser.ASpecContext ctx) {
System.out.println("visitASpec");
return null;
}
#Override
public Object visitBSpec(TParser.BSpecContext ctx) {
System.out.println("visitBSpec");
return null;
}
}
You can test this (in Java) like this:
String source = "... your input here ...";
TLexer lexer = new TLexer(CharStreams.fromString(source));
TParser parser = new TParser(new CommonTokenStream(lexer));
TestVisitor visitor = new TestVisitor();
visitor.visit(parser.thingList());
Good day! I need your help, I have next tests:
[SetUp]
public void SetUp()
{
controller = Substitute.For<IApplicationController>();
view = Substitute.For<ICamerasView>();
presenter = new CamerasPresenter(controller, view);
argument = InitializeDevicesList();
presenter.Run(argument);
}
private List<string> InitializeDevicesList()
{
List<string> devicesList = new List<string>();
Device device = new Device();
devicesList.Add(device.Name);
return devicesList;
}
[Test]
public void RunIfDeviceListIsNotEmpty()
{
view.DidNotReceive().SetUIOnNoConnectedDevices();
view.Received().FillCamerasListView(argument);
view.Received().Show();
}
which actually tests next code
public override void Run(List<string> argument)
{
connectedCameras = argument;
if(connectedCameras.Count == 0)
{
SetUIOnNoConnectedDevices();
}
else
{
FillCamerasListView();
}
View.Show();
}
And my issue is that FillCamerasListView method isn't calling in test. But as it expected it called in Run method in this case. So, I can't imagine what is the problem, so I will be very appreciated for your help. Thanks for your time!
This example passes. The problem appears to be something in your example that is changing the argument passed to FillCamerasListView as discussed in the comments.
A few options:
Modify the code to match the test's expectation. i.e. pass the argument given to Run on to FillCamerasListView.
Use view.ReceivedWithAnyArgs().FillCamerasListView(null) to assert a call was made without worry about the specifics of the argument passed.
Use view.Received().FillCamerasListView(Arg.Is<List<string>>(x => Matches(x, argument)), where Matches is your own code which determines whether the argument given is correct based on the argument passed to Run.
I am develeloping MVC application and writing the unit test.
I am confused about the coding pattern/process of unit test.
I am writing the unit test but I am not aware of , whether I am writing in proper way or not.
I am giving one example of the test case please check.
Basically, in test method I am writing the same code which I have written in GetPartiesByEmployee() method and I am comparing the no. of records which return from the method and the records return from code blog in test method is that correct ?
Is that correct ?
[TestMethod]
public void Test_Get_Parties_By_Employee_Method()
{
var actualResult = oPartyHelper.GetPartiesByEmployee(6);
Employee oEmployee = new Employee();
oEmployee = db.Employees.Find(6);
var roles = oEmployee.Roles.ToList();
List<Party> parties = new List<Party>();
foreach (Role item in roles)
{
var PartyCollection = from e in item.Parties.OrderBy(e => e.Name)
where (e.IsDeleted == false || e.IsDeleted == null)
select e;
parties.AddRange(PartyCollection.ToList());
}
parties=parties.Distinct().OrderBy(p => p.Id).ToList();
var expectedCount = parties.Count();
var actualList = (List<Party>)actualResult;
var actualCount = actualList.Count;
Assert.AreEqual(expectedCount, actualCount, "All parties are not same");
}
Actual Method :
public List<Party> GetPartiesByEmployee(int employeeId)
{
Employee oEmployee = new Employee();
oEmployee = db.Employees.Find(employeeId);
var roles = oEmployee.Roles.ToList();
List<Party> parties = new List<Party>();
foreach (Role item in roles)
{
var PartyCollection = from e in item.Parties.OrderBy(e => e.Name)
where (e.IsDeleted == false || e.IsDeleted == null)
select e;
parties.AddRange(PartyCollection.ToList());
}
return parties.Distinct().OrderBy(p=>p.Id).ToList();
}
No, this is not how unit testing works. You don't copy the same code into the test method, you test the actual object which has the code. (Just copying the code would not only create odd and probably unhelpful tests, but it would duplicate everything in the system, which is unmaintainable.)
So let's say you have a method like this:
public int ActualMethod()
{
var x = 0;
var y = 1;
return x + y;
}
You would not test that code by doing this:
[Test]
public void TestMethod()
{
var x = 0;
var y = 1;
Assert.Equal(1, x + y);
}
You should instead have something like this:
[Test]
public void TestMethod()
{
var testableObject = new SomeObject();
var expectedResult = 1;
var actualResult = testableObject.ActualMethod();
Assert.Equal(expectedResult, actualResult);
}
(Which you can modify for readability as you see fit. I was perhaps overly-explicit with the lines of code and variable names in that test method, just to demonstrate what's happening.)
The idea is that the unit tests load the actual module being tested, not copies of the lines of code. Think of it from an encapsulation point of view for object-oriented design. Nothing outside of those objects, including the tests themselves, should know anything about their internal implementations. The tests are just interacting with the objects and validating that the results match what's expected. The tests don't care how those objects internally achieve the results, only that the results meet expectations.
In general, unit tests follow three steps:
Arrange
Act
Assert
That is...
First, you arrange the objects for your test. This might involve resetting some static data into a known state, instantiating an object (or grabbing it from a factory, etc.), setting some properties, etc. Basically you're creating a known state from which a test will be run.
Second, you act upon that object. You perform some action which should change the state of the system in some way. Usually this is just calling a method on the object (or perhaps passing the object to a method somewhere else in some cases). This is what you're testing. That the code which changes the state of the system will change it from one known state to another expected resulting state.
Third, you assert the result of the test. Since you created a known state in the first step, changed the state in the second step, now you observe the resulting state in the third step.
You can use NUnit in several ways. It depends on your code and what your test is all about. In your case yes, comparing totals you would use the AreEqual method. Another common example is if you would like to see if a code generates exceptions or not - maybe to check library updates etc. Something similar to the following might be useful :
[TestCase]
public void TestCase()
{
try
{
// Write you code here that might generate an exception
Assert.AreEqual(true, true);
}
catch (Exception e)
{
Assert.Fail(e.Message, e.GetType().Name);
}
}
As you can see if the executes successfully I use AreEqual, and comparing true with true so it will execute fine. If however the code generates an exception, I'd send back the error messages.
I am using Entity Framework 4.0 and trying to use the "Contains" function of one the object sets in my context object. to do so i coded a Comparer class:
public class RatingInfoComparer : IEqualityComparer<RatingInfo>
{
public bool Equals(RatingInfo x, RatingInfo y)
{
var a = new {x.PlugInID,x.RatingInfoUserIP};
var b = new {y.PlugInID,y.RatingInfoUserIP};
if(a.PlugInID == b.PlugInID && a.RatingInfoUserIP.Equals(b.RatingInfoUserIP))
return true;
else
return false;
}
public int GetHashCode(RatingInfo obj)
{
var a = new { obj.PlugInID, obj.RatingInfoUserIP };
if (Object.ReferenceEquals(obj, null))
return 0;
return a.GetHashCode();
}
}
when i try to use the comparer with this code:
public void SaveRatingInfo2(int plugInId, string userInfo)
{
RatingInfo ri = new RatingInfo()
{
PlugInID = plugInId,
RatingInfoUser = userInfo,
RatingInfoUserIP = "192.168.1.100"
};
//This is where i get the execption
if (!context.RatingInfoes.Contains<RatingInfo>(ri, new RatingInfoComparer()))
{
//my Entity Framework context object
context.RatingInfoes.AddObject(ri);
context.SaveChanges();
}
}
i get an execption:
"LINQ to Entities does not recognize the method 'Boolean Contains[RatingInfo](System.Linq.IQueryable1[OlafCMSLibrary.Models.RatingInfo], OlafCMSLibrary.Models.RatingInfo,
System.Collections.Generic.IEqualityComparer1[OlafCMSLibrary.Models.RatingInfo])' method, and his method cannot be translated into a store expression."
Since i am not proficient with linQ and Entity Framework i might be making a mistake with my use of the "var" either in the "GetHashCode" function or in general.
If my mistake is clear to you do tell me :) it does not stop my project! but it is essential for me to understand why a simple comparer doesnt work.
Thanks
Aaron
LINQ to Entities works by converting an expression tree into queries against an object model through the IQueryable interface. This means than you can only put things into the expression tree which LINQ to Entities understands.
It doesn't understand the Contains method you are using, so it throws the exception you see. Here is a list of methods which it understands.
Under the Set Methods section header, it lists Contains using an item as supported, but it lists Contains with an IEqualityComparer as not supported. This is presumably because it would have to be able to work out how to convert your IEqualityComparer into a query against the object model, which would be difficult. You might be able to do what you want using multiple Where clauses, see which ones are supported further up the document.