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.
Related
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());
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
}
I am using the XMLUnit in JUnit to compare the results of tests. I have a problem wherein there is an Element in my XML which gets the CURRENT TIMESTAMP as the tests run and when compared with the expected output, the results will never match.
To overcome this, I read about using org.xmlunit.diff.NodeFilters, but do not have any examples on how to implement this. The code snippet I have is as below,
final org.xmlunit.diff.Diff documentDiff = DiffBuilder
.compare(sourcExp)
.withTest(sourceActual)
.ignoreComments()
.ignoreWhitespace()
//.withNodeFilter(Node.ELEMENT_NODE)
.build();
return documentDiff.hasDifferences();
My problem is, how do I implement the NodeFilter? What parameter should be passed and should that be passed? There are no samples on this. The NodeFilter method gets Predicate<Node> as the IN parameter. What does Predicate<Node> mean?
Predicate is a functional interface with a single test method that - in the case of NodeFilter receives a DOM Node as argument and returns a boolean. javadoc of Predicate
An implementation of Predicate<Node> can be used to filter nodes for the difference engine and only those Nodes for which the Predicate returns true will be compared. javadoc of setNodeFilter, User-Guide
Assuming your element containing the timestamp was called timestamp you'd use something like
.withNodeFilter(new Predicate<Node>() {
#Override
public boolean test(Node n) {
return !(n instanceof Element &&
"timestamp".equals(Nodes.getQName(n).getLocalPart()));
}
})
or using lambdas
.withNodeFilter(n -> !(n instanceof Element &&
"timestamp".equals(Nodes.getQName(n).getLocalPart())))
This uses XMLUnit's org.xmlunit.util.Nodes to get the element name more easily.
The below code worked for me,
public final class IgnoreNamedElementsDifferenceListener implements
DifferenceListener {
private Set<String> blackList = new HashSet<String>();
public IgnoreNamedElementsDifferenceListener(String... elementNames) {
for (String name : elementNames) {
blackList.add(name);
}
}
public int differenceFound(Difference difference) {
if (difference.getId() == DifferenceConstants.TEXT_VALUE_ID) {
if (blackList.contains(difference.getControlNodeDetail().getNode()
.getParentNode().getNodeName())) {
return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
}
return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
}
public void skippedComparison(Node node, Node node1) {
}
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.
How is it possible to call a delegated Method only once / one time with moles?
MyClass.AllInstances.ResultateGet = delegate { return new ResultatInfoCollection(); };
I want to call the Method "ResultateGet" only one time because the init is quite complex the first time without a delegate.
target.UpdateResultate(); //calls delegate "ResultateGet"
//Assert some stuff
target.Verify(); //needs original function "ResultateGet" so unit test is useful
I am generally interested how to call a moles delegate one time ore a specific number of times before the original function is called and not the delegate.
Update:
I found a way, that seems a little bit cumbersome. Any better Solution?
ResultatInfoCollection x = new ResultatInfoCollection();
MolesContext.ExecuteWithoutMoles(() => x = target.Resultate);
Also, see my answer to: How to assign/opt from multiple delegates for a 'moled' method? This provides an example of gating logic inside the anonymous method.
Ooh, good question! I have encountered this, myself. What you are looking for is called a "fallthrough" behavior (execution of the original code). The anonymous method to which Moles detours must contain a switching mechanism that falls through, after the first call. Unfortunately, I don't believe a fallthrough feature is included in Moles, at this time.
Your updated workaround is exactly what you need -- calling fallthrough would do the same thing. I suggest adding a sentinel value, doFallthrough, that gates the calls:
bool doFallthrough = false;
ResultatInfoCollection x = new ResultatInfoCollection();
MyClass.AllInstances.ResultateGet = delegate {
if (!doFallthrough)
{
doFallthrough = true;
return new ResultatInfoCollection();
}
MolesContext.ExecuteWithoutMoles(() => x = target.Resultate);
};
Calling a specific number of times simply requires a change to the sentinel value type:
int doFallthrough = 0;
ResultatInfoCollection x = new ResultatInfoCollection();
MyClass.AllInstances.ResultateGet = delegate {
if (++doFallthrough < 5)
return new ResultatInfoCollection();
MolesContext.ExecuteWithoutMoles(() => x = target.Resultate);
};
Old question, but since I found it when I was searching, I'll answer it for the next person with my solution.
Using MolesContext.ExecuteWithoutMoles to call the original function works just fine in most cases, however, if you are moling any other functions or classes downstream from this call, they won't be moled, either.
Given the following class:
public class TheClass
{
public int TheFunction(int input){
return input + TheOtherFunction();
}
public int TheOtherFunction(){
return DateTime.Now.Minutes;
}
}
If you use the MolesContext.ExecuteWithoutMoles approach:
MTheClass.AllInstances.TheOtherFunctionInt = (instance) => {
return 5;
};
MTheClass.AllInstances.TheFunctionInt = (instance, input) =>
{
//do your stuff here, for example:
Debug.WriteLine(input.ToString());
var result = MolesContext.ExecuteWithoutMoles<int>(() => instance.TheFunction(input));
//do more stuff, if desired
return result;
};
Your mole for OtherFunction will not be hit, because it was (indirectly) executed within the "without moles" scope.
However, you can add and remove moles delegates at any time, so that allows you to do the following, as outlined in the Moles Documentation (p. 24)
MTheClass.AllInstances.TheOtherFunctionInt = (instance) => {
return 5;
};
MolesDelegates.Func<TheClass, int, int> molesDelegate = null;
molesDelegate = (instance, input) =>
{
//do your stuff here, for example:
Debug.WriteLine(input.ToString());
int result = 0;
try{
MTheClass.AllInstances.TheFunctionInt = null;
result = instance.TheFunction(input);
}
finally{
MTheClass.AllInstances.TheFunctionInt = molesDelegate;
}
//do more stuff, if desired
return result;
};
MTheClass.AllInstances.TheFunctionInt = molesDelegate;
The OtherFunction moles is still hit. With this method, you can remove moling just from the specific method without impacting your other moles. I've used this, and it works. The only trouble I can see is that it won't work if you have a recursive function, or possibly a multi-threaded situation.