Moq: Verifying a method was called with a particular delegate produces "method argument length mismatch" - delegates

I've got a class A that calls a method on interface B, passing to it one of its own methods as sort of a continuation that B is supposed to call when it has a result. The code seems to work fine in practice, but I can't figure out how to test it with Moq -- when I try the obvious thing, it produces System.ArgumentException : method argument length mismatch. Thought at first it might be my code, but it fails the same way with the following toy case:
public class A
{
readonly B myB;
public A (B b)
{
myB = b;
}
public void HandleC (C c)
{
// do something
}
public void DoFindC ()
{
myB.FindC (HandleC);
}
}
public interface B
{
// Finds a C and then passes it to handleC
void FindC (Action<C> handleC);
}
public interface C
{
}
[TestFixture()]
public class ATest
{
[Test()]
public void TestDoFindC ()
{
Mock<B> bMock = new Mock<B> ();
A a = new A(bMock.Object);
a.DoFindC();
bMock.Verify(b => b.FindC(a.HandleC));
}
}
I'm guessing there's some behind-the-scenes magic with delegates that I don't understand yet, being relatively new to C#, but what's the right way to test this?
Update: For reference, I'm using Mono 2.6.7 on MacOS 10.6.5 and targeting .NET 3.5.
Updated again: Best guess is that this is a Mono bug; I've filed it as https://bugzilla.novell.com/show_bug.cgi?id=656918.

Mono bug: https://bugzilla.novell.com/show_bug.cgi?id=656918.

Related

The fact that the type of function determined in runtime is defined as advantage?

I read that one advantage of using by "inheritance" for generic-code is "the fact that the type of the object determined in runtime", because that allows more flexibility.
I don't understand this point. How it's really allows more flexibility?
If for example I get object from type that derived Base , so that:
class Base{
public:
virtual void method() const { /* ... */ }
};
class D1 : public Base{
public:
void method() const override { /* ... */ }
};
class D2 : public Base{
public:
void method() const override { /* ... */ }
};
And I send to function f (for example) the following object:
Base* b = new D1;
f(b);
Where is the flexibility (What it's defined as advantage that it's done in runtime) ?
Your example isn't demonstrating it, but it could.
f(b) could be
void f(Base* b) {
b->method();
}
Now, the actual method() code that's executed is determined at runtime by the type of the object that's passed in.
How it's really allows more flexibility?
It's more flexible because the author of f(..) doesn't need to know how Base:method() works in any specific case: You can add D3, D4, D5 classes with new implementations of method() without f(..) ever needing to know or change.

how to test fluent validations error message

I am trying to get to grips with TDD, I have reviewed some tutorials and am trying to implement tests on my validation classes that I have created using fluent validation.
public SomeFormValidator()
{
RuleFor(x => x.MyClass).NotNull()
.WithMessage("MyClass cannot be null");
}
I have looked at the TDD examples specifically for fluent validation and created a couple of tests
[Test]
public void Should_have_error_when_MyClass_is_null()
{
MyClass myClass = null;
SomeFormValidator.ShouldHaveValidationErrorFor(aup => aup.MyClass, myClass);
}
[Test]
public void Should_not_have_error_when_MyClass_is_not_null()
{
MyClass myClass = new MyClass();
SomeFormValidator.ShouldNotHaveValidationErrorFor(aup => aup.MyClass, myClass);
}
I would like to now test that the string "MyClass cannot be null" is returned when it is null. I have not been able to find anything covering returned message and I have not been able to work it out.
Thanks to the guidance of #Surgey I was able to come up with a solution that uses the fluent validation built in methods, in addition to that I have been able to better layout my test which I have added below
using FluentValidation.TestHelper;
using NUnit.Framework;
using MyProject.Models...
using MyProject...
namespace MyProject.Tests.Classes.Validation
{
[TestFixture]
public class SomeFormValidatorTest
{
private SomeFormValidator SomeFormValidator;
[SetUp]
public void Setup()
{
SomeFormValidator = new SomeFormValidator();
}
[Test]
public void Should_display_correct_error_message_MyClass_is_null()
{
//arrange
MyClass myClass = null;
//act
var result = SomeFormValidator.ShouldHaveValidationErrorFor(x => x.MyClass, myClass);
//assert
result.WithErrorMessage("MyClass is required");
//first attempt prior to finding WithErrorMessage exists
//foreach (var r in result)
//{
// Assert.AreEqual("MyClass is required", r.ErrorMessage);
//}
}
}
}
I am using result.WithErrorMessage as that is was is provided in the result but I have left the foreach in, but commented, as I find the error message produced by using Assert.AreEqual produce a better message in the test runner.
There is Arrange-Act-Assert (AAA) technique that helps to structure unit tests properly.
Arrange
First of all, you need to create a System Under Test (SUT) and inputs. In this case that are SomeFormValidator and SomeForm instances:
// arrange
var sut = new SomeFormValidator();
var someFormWithNullProp = new SomeForm { MyClass = null };
Act
Then you need to call the SUT to perform real work. For validators, that is the Validate() method call:
// act
ValidationResult result = sut.Validate<SomeForm>(someFormWithNullProp);
Assert
The last part of the unit test checks if the actual result matches the expectations:
// assert
Assert.False(result.IsValid);
Assert.AreEqual(
"MyClass cannot be null",
result.Errors.Single().ErrorMessage);

Using Gtest how to check if the return type is an expected object or not?

I am using Gtest for unit testing. There are some methods which return an object. Example is shown below
Class ToTest{
public:
object& method(){
object* obj = new object();
return obj;
}
}
"ToTest" is the class that is to be tested. It has a method which returns an object "obj". How can i validate this object using Gtest ?
So, you want to test a singleton. As you see, there is almost nothing to test there. You can call that method, and that is it. There is nothing to validate, except there are no leaks (by executing the unit test program using valgrind or similar tool).
class ToTestTest : public testing::Test
{
public:
ToTestTest()
{
}
~ToTestTest()
{
}
ToTest obj;
};
TEST_F( ToTestTest, method )
{
obj.method();
}

How can I apply the "move method" refactoring with IntelliJ IDEA?

I want to be able to move an instance method from one class to another class ("Move method" from Fowler's "Refactoring") in IntelliJ IDEA. Unfortunately, when I try "Move..." (cmd: F6), it tells me that "There are no methods that have a reference type. Would you like to make method static and then move?" I do not want to make my method static, I want it to be an instance method on the other class instead.
My code example:
public class TheClass {
public void doStuff(){
int i = themethod();
}
private int theMethod() {
System.out.println( "Hello World!" );
return 0;
}
}
public class OtherClass {
}
Say I want to move theMethod from TheClass to OtherClass. Is there an automatic refactoring in IDEA for this, and if so: How do I apply it?
In IntelliJ 14-15 do the following:
Position the caret on theMethod().
press Ctrl/Cmd+F6 (Change signature).
Introduce new parameter: Type=TheOtherClass, Name=theOtherClass, Default value=new TheOtherClass()
Refactor
Then press F6 (move) and move the method to theOtherClass.
You will end up with:
public class TheClass {
public void doStuff() {
int i = new TheOtherClass().theMethod();
}
}
public class TheOtherClass {
int theMethod() {
System.out.println("Hello World!");
return 0;
}
}
The Move Method refactoring in IDEA only considers moving the method into classes related to it, i.e. used as its parameter or return value, or called from inside the method. Which is kinda logical: if the method has nothing concrete to do with the target class, why should it be there? OTOH I found this limiting in some cases where I still had a valid reason to move the method. So I had to do it by hand.
In intellij 13.1 (dont' know in previous version) it could be done with the
Choose Refactor | Extract | Delegate on the main menu
but there is a "strange" limit, apparently: it could be done only with a new freshly created class.
So you have to do apply this refactoring without creating the "OtherClass" (it will be create directly when you apply the refactoring).
So a real "move" of method on an alredy created class seems missing, quite strange behaviou
if theMethod() has nothing reference to the host class(TheClass), you can make this method static and then use "Move" command. After the method was moved to the target class, you should remove the static keyword.
There is another method. Imagine you have the code:
public int field;
public void foo(int a) {
assert field == a;
}
And you want to make foo static. Select the whole body of the method and preess Alt+Ctrl+M (Extract method). Type the same name of the method. Check "Declare static" checkbox (available only if the method only reads and doesn't modify the fields) and press Ok. So you get:
public void foo(int a) {
foo(a, field);
}
private static void foo(int a, int field) {
assert field == a;
}
Move static method wherever you want and use old foo's body to call it.

Simple MVC NerdDinners Lambda

In this code from Microsoft's MVC Tutorial NerdDinners:
public class DinnerRepository {
private NerdDinnerDataContext db = new NerdDinnerDataContext();
//
// Query Methods
public IQueryable<Dinner> FindAllDinners() {
return db.Dinners;
}
public IQueryable<Dinner> FindUpcomingDinners() {
return from dinner in db.Dinners
where dinner.EventDate > DateTime.Now
orderby dinner.EventDate
select dinner;
}
public Dinner GetDinner(int id) {
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
//
// Insert/Delete Methods
public void Add(Dinner dinner) {
db.Dinners.InsertOnSubmit(dinner);
}
public void Delete(Dinner dinner) {
db.RSVPs.DeleteAllOnSubmit(dinner.RSVPs);
db.Dinners.DeleteOnSubmit(dinner);
}
//
// Persistence
public void Save() {
db.SubmitChanges();
}
}
What does:
public Dinner GetDinner(int id) {
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
the "d" mean? How does this code work? I know it it bringing back dinners where dinnerid matches id from the function parameter. I don't understand the "d goes to..." means. I know it is a lambda but I don't really get it. What is the "d" for? What does it do?
Could this have been written without the lambda here (how)?
You should probably read up on anonymous methods.
Basically the code you are referring to can be written as an anonymous method without lamba syntax like this:
public Dinner GetDinner(int id) {
return db.Dinners.SingleOrDefault(delegate (Dinner d) {
return d.DinnerID == id;
});
}
This is similar too...
from d in db.Dinners
where d.DinnerID == id
select d
The code basically loops around the dinners returning the first Dinner or the default if none is found.
This is a case where the naming conventions used in a sample aren't always appropriate in production. Using a "d" as a local variable is usually fround upon and choosing a variable name of "dinner" would probably be more appropriate, although in this case the scope of d is so small it is clear either way, as long as you know how lambda expressions work.
You need to understand lambda syntax and what it's used for.
Here's an article that does a decent job of explaining it.
However, to shortly answer your question in regards to the NerdDinner context, "d" in this context is just a parameter passed into the lamda expression that is a Dinner object.
This bit of code:
d => d.DinnerID == id
Can be thought of as defining a function of type Func<Dinner, bool>.
Whatever you pass it to, this function can be called, and passed Dinner, and it will give back a bool.
void Foo(Func<Dinner, bool> f)
{
bool result = f(new Dinner());
}
In your real example, the function SingleOrDefault will call the function you give it multiple times, passing it a different Dinner each time, and will return the Dinner for which the function returns true.
In fact, as you're using IQueryable, this is only conceptually what happens. The chances are, the code of the function is converted into SQL, and all the execution is done inside the database.

Resources