Mocking MailController with ActionMailer.net using Moq 3 - asp.net-mvc-4

I'm new to Moq, so any help would be great. I keep getting a null reference error in my code when I'm trying to set up a test. Here is the line of code where I'm getting the error below.
_iMailController.RequesterEmail(model).Deliver();
Here is what my test looks like:
_mockMailController = new Mock<IMailController>();
mockMailController .Setup(x => x.RequesterEmail(new Model())).Returns(**new EmailResult()**);
The bold part is where I'm stuck at. It takes 7 parameters and dont know what to put to fake out the EmailResult.

You are confusing, The Return part will single return values like string, list, bool or Int ect.
So you can easily pass the value which you get in return on the RequesterEmail on the IMailController. So you have to check the which value get retun from the RequesterEmail method.
You may also use the below code as example:
mockMailController .Setup(x => x.RequesterEmail(It.IsAny<Model>())).Returns(**new EmailResult()**);
Refet the below Part too.
It mentioned about how many parameter you passed in the RequesterEmail method. If there is 7 parameters passed on the method then you may have to pass 7 parmeter like bleow
Please look deeply in parameter and return on both codes down here.
And look where i use ModelClass in both below codes.
If the Method have parameters like below:
public void RequesterEmail( string, int, list, EmailClass, someClass, bool, string);
{
return ModelClass;
}
then you may have to write the code as below
mockMailController .Setup(x => x.RequesterEmail(It.IsAny<string>(), It.IsAny<int>(),
It.IsAny<EmailClass>(), It.IsAny<someClass>(), It.IsAny<bool>(),
It.IsAny<string>())).Return(ModelClass)

Related

How to test #type decorator in NestJs using jest? [duplicate]

I am asking you for help. I have created a DTO that looks like it (this is a smaller version) :
export class OfImportDto {
#IsString({
message: "should be a valid product code"
})
productCode: string;
#IsString({
message: "Enter the proper product description"
})
productDescription: string;
#IsDateString({
message: "should be a valid date format, for example : 2017-06-07T14:34:08+04:00"
})
manufacturingDate : Date
#IsInt({
message: "should be a valid planned quantity number"
})
#IsPositive()
plannedQuantity: number;
the thing is that i am asking to test that, with a unit test and not a E2E test. And I Don't know how to do that. For instance, I would like to unit test
1/ if my product code is well a string, a string should be created, if not, throw my exception
2/ if my product description is well a string, a string should be created, if not, throw my exception
...
and so on.
So, can I made a spec.ts file to test that? If yes, how?
If not, is it better to test it within the service.spec.ts? If so, how?
Thank you very much, any help would be very helpful :)
You should create a separate DTO specific file like of-import.dto.spec.ts for unit tests of your DTOs. Let's see how to test a DTO in Nest.js step by step.
TLDR: Your DTO's unit test
To understand it line by line, continue reading:
it('should throw when the planned quantity is a negative number.', async () => {
const importInfo = { productCode: 4567, plannedQuanity: -10 }
const ofImportDto = plainToInstance(OfImportDto, importInfo)
const errors = await validate(ofImportDto)
expect(errors.length).not.toBe(0)
expect(stringified(errors)).toContain(`Planned Quantity must be a positive number.`)
}
Create a plain object to test
The following is an object that you would like to test for validation:
const importInfo = { productCode: 4567, plannedQuanity: -10 }
If your test object has nested objects or it's too big, you can skip those complex properties. We'll see how to deal with that.
Convert the test object to the type of DTO
Use plainToinstace() function from the class-transformer package:
const ofImportDto = plainToInstance(OfImportDto, importInfo)
This will turn your plain test object to the object of the type of your DTO, that is, OfImportDto.
If you have any transformations in your DTO, like trimming spaces of the values of properties, they are applied at this point. If you just intend to test the transformations, you can assert now, you don't have to call the following validate() function for testing transformations.
Emulate the validation
Use the validate() function from the class-validator package:
const errors = await validate(ofImportDto)
If you skipped some properties while creating the test object, you can deal with that like the following:
const errors = await validate(ofImportDto, { skipMissingProperties: true })
Now the validation will ignore the missing properties.
Assert the errors
Assert that the errors array is not empty and it contains your custom error message:
expect(errors.length).not.toBe(0)
expect(stringified(errors)).toContain(`Planned Quantity must be a positive number.`)
Here stringified() is a helper function to convert the errors object to a JSON string, so we can search if it contains our custom error message:
export function stringified(errors: ValidationError[]): string {
return JSON.stringify(errors)
}
That's it! Hope that helps.
It would be possible to create a OfImportDTO.spec.ts file (or whatever your original file is called), but the thing is, there isn't any logic here to test. The closest thing you could do is create an instance of a Validator from class-validator and then instantiate an instance of the OfImportDto and then check that the class passes validation. If you add logic to it (e.g. getters and setters with specific functions) then it could make sense for unit testing, but otherwise, this is basically an interface being called a class so it exists at runtime for class-validator

Reference value of constant with KDoc

I have a object like the following in my project
object UrlUtils {
private const val PARAM = "whatever"
/**
* Method that appends the [PARAM] parameter to the url
*/
fun appendParameter(url: String) {
// ...
}
}
As you can see a I wanna reference the value of the PARAM field in the KDoc comment of the appendParameter method however when looking at the comment I don't see the actual value but only the name of the field.
Method that appends the PARAM parameter to the url
What I want:
Method that appends the whatever parameter to the url
In Javadoc this works by using {#value PARAM} but there seems to be nothing similar in KDoc. Even the automatic code-converter keeps the old Javadoc.
So my question: Am I missing something or is KDoc/Dokka missing this feature?
Currently, {#value} tags are not supported by KDoc.
The closest issue requesting this is #488, so you can up-vote and/or comment on it.

dojo 1.7 QueryReadStore parameters

I am new to Dojo, I am using QueryReadStore as the store for loading my TreeGrid, working fine. But the QueryReadStore appends some paramters to the url, parameters like parentId, count, sort etc., I have looked at this link http://dojotoolkit.org/reference-guide/1.7/dojox/data/QueryReadStore.html, but not able to understand.
Parameters are getting passed like this servlet/DataHandler?start=0&count=25
How to manipulate the parameters, like I want to set the value for parentId paramters so that I only get that particular row details.
In theory you wold have to create a new class by extending the "dojox.data.QueryReadStore", in the link you posted have an example for doing exactly what you want. See if you get it now(changed a bit):
dojo.require("dojox.data.QueryReadStore");
dojo.declare("custom.MyReadStore", dojox.data.QueryReadStore, {
fetch:function(request){
//append here your custom parameters:
var qs = {p1:"This is parameter 1",
q:request.query.name
}
request.serverQuery = qs;
// Call superclasses' fetch
return this.inherited("fetch", arguments);
}
});
So When come to create the QueryReadStore you actually create a object with the class you defined. something like this:
var queryReadStore = new custom.MyReadStore({args...})
Explore the request parameter passed to the function to see what else you can do.

Why does this Machine.Fakes parameter matching throw an exception?

I'm using Machine.Fakes.NSubstitute and want to "fake" a return value such that if the input parameter matches a specific value it returns the mock object, otherwise it returns null.
I tried the following:
host.WhenToldTo(h => h.GetTenantInstance(Param.Is(new Uri("http://foo.bar"))))
.Return(new TenantInstance());
But it throws the following exception:
System.InvalidCastException: Unable to cast object of type
'System.Linq.Expressions.NewExpression' to type
'System.Linq.Expressions.ConstantExpression'.
My current workaround is to do the following:
host.WhenToldTo(h => h.GetTenantInstance(Param.IsAny<Uri>()))
.Return<Uri>(uri => uri.Host == "foo.bar" ? new TenantInstance() : null);
Which is a bit smelly.
I see three aspects here:
When a method with a reference type return value is called on a mock object and no behavior has been set up for the call, the mock object will return a mock. If you want it to return null instead, you have to configure that explicitly. Thus, it is not enough to set up
host.WhenToldTo(h => h.GetTenantInstance(Param.Is(new Uri("http://foo.bar"))))
.Return(new TenantInstance());
You also have to set up the other case with something like this:
host.WhenToldTo(h => h.GetTenantInstance(Param<Uri>.Matches(x => !x.Equals(new Uri("http://foo.bar")))))
.Return((TenantInstance)null);
I find your "workaround" solution more elegant than these two setups.
When you match a method call argument for equality, there is no need to use Param.Is(). You can simply set up the behavior with
host.WhenToldTo(h => h.GetTenantInstance(new Uri("http://foo.bar")))
.Return(new TenantInstance());
The fact that you get an exception when using Param.Is() here is a shortcoming of Machine.Fakes. I see not reason why this should not work. I will correct that at some point and let you know.

Is it possible to pass a variable's name along with the value, when passing through functions?

I want to know if it's possible to retrieve the variables name from when it was passed into a certain function. For example, if I call parseId(myId) to a function with the signature parseId(id), i can obviously retrieve the value of 'id'. However, is there any way I can retrieve 'myId' as a string (without passing it as another value)?
Specifically in vb.net, but I'm interested in how it would work in any given language.
This is all just random thoughts.. feel free to dismiss or not ;-p
Re your comment about use with stored procedures... if you want to go that route, I wouldn't mess around with the local variable names; that is an implementation detail. However, you could expose those details on an interface method and use the names from there, since that is more formalised - for example (C#):
interface ICustomerRepository {
Customer GetById(int id); // perhaps an attribute to name the sproc
}
You can use similar expression-tree parsing (as discussed here) to get the name and value of the parameter, for example:
var repoWrapper = new Repo<ICustomerRepository>();
int custId = 12345;
var cust = repoWrapper.Execute(r => r.GetById(custId));
Here we'd want to resolve the argument to GetById as "id" (not "custId"), with value 12345. This is actually exactly what my protobuf-net RPC code does ;-p (just don't ask me to translate it to VB - it is hard enough to write it in a language you know well...)
No, you can't do that in the normal sense. What are you really trying to accomplish with this?
You can do this in .NET 3.5 and above using expression trees; I'll knock up a C# example, and try to run it through reflector for VB...
C#:
static void Main()
{
int i = 17;
WriteLine(() => i);
}
static void WriteLine<T>(Expression<Func<T>> expression)
{
string name;
switch (expression.Body.NodeType)
{
case ExpressionType.MemberAccess:
name = ((MemberExpression)expression.Body).Member.Name;
break;
default:
throw new NotSupportedException("Give me a chance!");
}
T val = expression.Compile()();
Console.WriteLine(name + "=" + val);
}
The VB is below, but note that the VB compiler seems to use different names (like $VB$Local_i, not i):
Sub Main()
Dim i As Integer = 17
WriteLine(Function() i)
End Sub
Private Sub WriteLine(Of T)(ByVal expression As Expression(Of Func(Of T)))
If (expression.Body.NodeType <> ExpressionType.MemberAccess) Then
Throw New NotSupportedException("Give me a chance!")
End If
Console.WriteLine((DirectCast(expression.Body, MemberExpression).Member.Name
& "=" & Convert.ToString(expression.Compile.Invoke)))
End Sub