I am writing unit tests of controller logic with Xunit.
One of my controller actions returns a BadRequestObjectResult with the ModelStateDictionary object:
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
To do this my test case adds a ModelState error like this:
controller.ModelState.AddModelError("Test", "This is a test model error");
In the Assert statements of my test case I am checking the return object which is type SerializableError:
var returnError = Assert.IsType<SerializableError>(objectResult.Value);
Assert.Single(returnError);
Assert.True(returnError.ContainsKey("Test"));
Assert.True(returnError.ContainsValue("This is a test model error"));
The Assert.Single(returnError); and Assert.True(returnError.ContainsKey("Test")); checks pass successfully as expected.
However, the check on the check of the error value fails (it returns false but I expect it to return true):
Assert.True(returnError.ContainsValue("This is a test model error"));
I can see from debugging that the Value seems to be nested in an extra string object:
But I have been unable to write a test which tests the value. How do I do it?
As mentioned in another answer, value of Dictionary is an array, so you should address that in the assertions.
var returnError = Assert.IsType<SerializableError>(objectResult.Value);
var errors = objectResult.Value as SerializableError;
Assert.Single(errors);
Assert.True(errors.ContainsKey("Test"));
var errorValues = returnError["Test"] as string[];
Assert.Single(errorValues);
Assert.True(errorValues.Single() == "This is a test model error");
Because SerializableError inherits from Dictionary, you should be able to do it in clearer way with help of FluentAssertions library
var expected = new SerializableError
{
{ "Test", new[] {"This is a test model error"}},
};
objectResult.Value.Should().BeOfType<SerializableError>();
objectResult.Value.Should().BeEquivalentTo(expected);
Your value is a list. so Value[0] or Value.First(). It' a keyvaluepair so you should be able to access it by returnError[keyName].
You need to cast the response to ObjectResult see below
var result = response.Result as BadRequestObjectResult
or
var result = response.Result as OkObjectResult
now you can access the value using result.Value property
Related
I am very new to unit tests and recently started learning it from various online resources.
But still it confuses me when I need to implement it in my code.
For the given image which I have attached here, could anyone of you suggest me how should I start or where to start?
This is Azure function which I will be creating unit test for, framework/library I would prefer is Xunit and moq.
As mentioned in a comment, a good place to start when unit testing is looking at your code and identifying the different "paths" it can take and what the result of that path will be.
if (inventoryRequest != null)
{
// path 1
await _inventoryService.ProcessRequest(inventoryRequest);
_logger.LogInformation("HBSI Inventory Queue trigger function processed.");
}
else
{
// path 2
_logger.LogInformation("Unable to process HBSI Rate plan Queue.");
}
In your code, because of your if statement, there are 2 possible paths which will end in 2 different results = 2 unit tests.
Now you can start creating your unit tests but first you need to find out what you need to set up to be able to trigger your code.
private readonly ILogger _logger;
private readonly IInventoryService _inventoryService;
public InventoryServiceBusFunction(ILogger logger, IInventoryService inventoryService)
{
_logger = logger;
_inventoryService = inventoryService;
}
You have some dependencies being passed into your constructor with interfaces - great, this means we can mock them. We want to mock dependencies in unit tests because we want to control their behaviour for the tests. Also, mocking the dependencies negates any "real" behaviour the dependency might be performing i.e. database operations, API calls etc.
Using Moq we can mock the objects like so:
public class InventoryServiceBusFunctionTests
{
private readonly Mock<ILogger> _mockLogger = new Mock<ILogger>();
private readonly Mock<IInventoryService> _mockInventoryService = new Mock<IInventoryService>();
...
We will use these mocks later to make verifications on behaviour we expect to happen.
Next, we need to create an instance of the actual class we want to test.
// using a constructor in the test class will run this code before each test
public InventoryServiceBusFunctionTests()
{
// pass the mocked objects to initialize class
_inventoryServiceBusFunction = new InventoryServiceBusFunction(_mockLogger.Object, _mockInventoryService.Object);
}
Now that we have an instance of the InventoryServiceBusFunction class, we can use any of the public properties/methods in our tests.
[Fact]
public async Task GivenInventoryRequest_WhenFunctionRuns_ThenInventoryServiceProcessesRequest()
{
Now, remembering the paths from earlier, we can start to create the test cases. We can take the first path and create a [Fact] for it. You want to give your test case a meaningful name. I usually use the style of Given_When_Then to describe what is expected to happen.
Next, I usually add 3 comment sections to my test case:
// arrange
// act
// assert
This allows me to clearly see which parts of the test are doing what.
// act
await _inventoryServiceBusFunction.Run(inventoryRequest);
Next, I would fill in the \\ act section because this will tell me (via Intellisense) what I need to arrange. e.g. above, when hovering my mouse over the Run method, I can see that I need to pass an instance of InventoryRequest.
// arrange
var inventoryRequest = new InventoryRequest
{
Name = "abc123",
Quantity = 2,
Tags = new List<string>
{
"foo"
}
};
In the \\ arrange section, initialize an instance of the InventoryRequest class and set the properties. This can be any data as we aren't really interested in the data itself but more what happens when the code runs.
if (inventoryRequest != null)
{
// path 1
await _inventoryService.ProcessRequest(inventoryRequest);
_logger.LogInformation("HBSI Inventory Queue trigger function processed.");
}
Lastly, the \\ assert section. Here, we want to make assertions on what we expect to happen given the set up of the test. So given the InventoryRequest is not null, we expect the if to evaluate to true and we expect the _inventoryService.ProcessRequest(inventoryRequest) method to be executed.
// assert
_mockInventoryService
.Verify(x => x.ProcessRequest(It.Is<InventoryRequest>(ir => ir.Name == inventoryRequest.Name
&& ir.Quantity == inventoryRequest.Quantity
&& ir.Tags.Contains(inventoryRequest.Tags[0]))));
In Moq, we can use the .Verify() method on the mock object to assert that the method was called. We can use the It.Is<T> syntax to make assertions on the data that is passed to the method.
Here is the full test case for path 1:
[Fact]
public async Task GivenInventoryRequest_WhenFunctionRuns_ThenInventoryServiceProcessesRequest()
{
// arrange
var inventoryRequest = new InventoryRequest
{
Name = "abc123",
Quantity = 2,
Tags = new List<string>
{
"foo"
}
};
// act
await _inventoryServiceBusFunction.Run(inventoryRequest);
// assert
_mockInventoryService
.Verify(x => x.ProcessRequest(It.Is<InventoryRequest>(ir => ir.Name == inventoryRequest.Name
&& ir.Quantity == inventoryRequest.Quantity
&& ir.Tags.Contains(inventoryRequest.Tags[0]))));
}
Then for path 2, you are setting up the test so that the else condition is executed.
[Fact]
public async Task GivenInventoryRequestIsNull_WhenFunctionRuns_ThenInventoryServiceDoesNotProcessRequest()
{
// arrange
InventoryRequest inventoryRequest = null;
// act
await _inventoryServiceBusFunction.Run(inventoryRequest);
// assert
_mockInventoryService
.Verify(x => x.ProcessRequest(It.IsAny<InventoryRequest>()), Times.Never);
}
Note - in the \\ assert here, I am asserting that the await _inventoryService.ProcessRequest(inventoryRequest) method is never called. This is because you want the test to fail in this scenario as the method should only be executed in the if condition. You may also choose to verify that the logger method is called with the correct message.
I'm using Junit 5.
This is my test:
#Test
void testCanCreateRefreshToken() {
var usersEntity = UsersEntity.builder().id(7L).username("username").password("thisIsAPassword").build();
var refreshTokensEntity = validRefreshTokensEntity(null, "this.is.token", usersEntity, Instant.now());
var savedRefreshTokensEntity = validRefreshTokensEntity(1L, "this.is.token", usersEntity, Instant.now());
when(usersRepository.findById(7L)).thenReturn(Optional.of(usersEntity));
when(refreshTokensRepository.save(refreshTokensEntity)).thenReturn(savedRefreshTokensEntity);
assertEquals(savedRefreshTokensEntity, refreshTokensService.createRefreshToken(7L));
}
And this is the method:
public RefreshTokensEntity createRefreshToken(Long userId) {
RefreshTokensEntity refreshTokensEntity = new RefreshTokensEntity();
refreshTokensEntity.setUsersEntity(usersRepository.findById(userId).get());
refreshTokensEntity.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
refreshTokensEntity.setToken(UUID.randomUUID().toString());
RefreshTokensEntity saved = refreshTokensRepository.save(refreshTokensEntity);
return saved;
}
System.out.println of refreshTokenEntity in real method:
RefreshTokensEntity(id=null, token=85c448be-11d2-43c6-8cc4-41f3a68fe4cb, usersEntity=UsersEntity(id=7, username=username, password=thisIsAPassword), expiryDate=2022-02-28T20:13:38.056212944Z)
System.out.println of refreshTokenEntity in test:
RefreshTokensEntity(id=null, token=this.is.token, usersEntity=UsersEntity(id=7, username=username, password=thisIsAPassword), expiryDate=2022-02-28T20:13:26.332206931Z)
Of course, if I pass any() I can validate test.
Is it possible the issues are the token and the expiryDate? So, I need to place them in a external class and mocked them...
I leave my own answer for somebody that can have same issue.
Yes, the issue was the variable values of token and ExpiryDate.
So, I create two different classes to manipulate them and use them as mocked.
So I can have same value in every test.
E.g.:
String refreshToken = "this-is-a-refreh-token";
when(jwtUtils.generateRefreshToken()).thenReturn(refreshToken);
I'm using NUnit 3 TestCaseData objects to feed test data to tests and Fluent Assertions library to check exceptions thrown.
Typically my TestCaseData object contains two parameters param1 and param2 used to create an instance of some object within the test and upon which I then invoke methods that should/should not throw exceptions, like this:
var subject = new Subject(param1, param2);
subject.Invoking(s => s.Add()).Should().NotThrow();
or
var subject = new Subject(param1, param2);
subject.Invoking(s => s.Add()).Should().Throw<ApplicationException>();
Is there a way to pass NotThrow() and Throw<ApplicationException>() parts as specific conditions in a third parameter in TestCaseData object to be used in the test? Basically I want to parameterize the test's expected result (it may be an exception of some type or no exception at all).
[TestCaseData] is meant for Test Case Data, not for assertions methods.
I would keep the NotThrow and Throw in separate tests to maintain readability.
If they share a lot of setup-logic, I would extract that into shared methods to reduce the size of the test method bodies.
TestCaseData accepts compile time values, whereas TestCaseSource generates them on runtime, which would be necessary to use Throw and NotThrow.
Here's a way to do it by misusing TestCaseSource.
The result is an unreadable test method, so please don't use this anywhere.
Anyway here goes:
[TestFixture]
public class ActionTests
{
private static IEnumerable<TestCaseData> ActionTestCaseData
{
get
{
yield return new TestCaseData((Action)(() => throw new Exception()), (Action<Action>)(act => act.Should().Throw<Exception>()));
yield return new TestCaseData((Action)(() => {}), (Action<Action>)(act => act.Should().NotThrow()));
}
}
[Test]
[TestCaseSource(typeof(ActionTests), nameof(ActionTestCaseData))]
public void Calculate_Success(Action act, Action<Action> assert)
{
assert(act);
}
}
I ended up using this:
using ExceptionResult = Action<System.Func<UserDetail>>;
[Test]
[TestCaseSource(typeof(UserEndpointTests), nameof(AddUserTestCases))]
public void User_Add(string creatorUsername, Role role, ExceptionResult result)
{
var endpoint = new UserEndpoint(creatorUsername);
var person = GeneratePerson();
var request = GenerateCreateUserRequest(person, role);
// Assertion comes here
result(endpoint.Invoking(e => e.Add(request)));
}
private static IEnumerable AddUserTestCases
{
get
{
yield return new TestCaseData(TestUserEmail, Role.User, new ExceptionResult(x => x.Should().Throw<ApplicationException>())
.SetName("{m} (Regular User => Regular User)")
.SetDescription("User with Regular User role cannot add any users.");
yield return new TestCaseData(TestAdminEmail, Role.Admin, new ExceptionResult(x => x.Should().NotThrow())
)
.SetName("{m} (Admin => Admin)")
.SetDescription("User with Admin role adds another user with Admin role.");
}
}
No big issues with readability, besides, SetName() and SetDescription() methods in the test case source help with that.
Request you to help me find the solution of below issue.
I have one function and corresponding Jasmine test case, like the one written below.
If I use angular.copy (and I have to use this only) in my function, Jasmine test case fails and error shown is expected 'originalValue' to equal 'newValue'.
If I use var obj = param1 (and not angular.copy) then Jasmine test case executes successfully.
I have to use angular.copy and at the same time, want jasmine test case to pass. Please help.
function
function func(param1, param2, condition)
{
var obj = angular.copy(param1);
if(condition){
obj.prop = param2;
}
}
jasmine test case
it('xxxx', function(){
var param = {'prop': ''};
var obj = {'prop': 'orignialValue'};
func(param, 'newValue', true);
expect(obj.prop).toEqual('newValue');
});
The example you provided is incorrect.
it('xxxx', function(){
var obj = {'prop': 'orignialValue'};
func(param, 'newValue', true);
expect(obj.prop).toEqual('newValue');
});
param is not defined over here, this should be obj I assume.
Since you use angular.copy, obj.prop is not added by ref to param1.
I found the solution. Instead of doing angular.copy inside the function func, I am first doing angular.copy and then passing this copied object to function func as its first parameter (param1).
I would like to pass a complete JSON object to a java adapter in worklight. This adapter will call multiple other remote resources to fulfill the request. I would like to pass the json structure instead of listing out all of the parameters for a number of reasons. Invoking the worklight procedure works well. I pass the following as the parameter:
{ "parm1": 1, "parm2" : "hello" }
Which the tool is fine with. When it calls my java code, I see a object type of JSObjectConverter$1 being passed. In java debug, I can see the values in the object, but I do not see any documentation on how to do this. If memory serves me, the $1 says that it is an anonymous inner class that is being passed. Is there a better way to pass a json object/structure in adapters?
Lets assume you have this in adapter code
function test(){
var jsonObject = { "param1": 1, "param2" : "hello" };
var param2value = com.mycode.MyClass.parseJsonObject(jsonObject);
return {
result: param2value
};
}
Doesn't really matter where you're getting jsonObject from, it may come as a param from client. Worklight uses Rhino JS engine, therefore com.mycode.MyClass.parseJsonObject() function will get jsonObject as a org.mozilla.javascript.NativeObject. You can easily get obj properties like this
package com.mycode;
import org.mozilla.javascript.NativeObject;
public class MyClass {
public static String parseJsonObject(NativeObject obj){
String param2 = (String) NativeObject.getProperty(obj, "param2");
return param2;
}
}
To better explain what I'm doing here, I wanted to be able to pass a javascript object into an adapter and have it return an updated javascript object. Looks like there are two ways. The first it what I answered above a few days ago with serializing and unserializing the javascript object. The other is using the ScriptableObject class. What I wanted in the end was to use the adapter framework as described to pass in the javascript object. In doing so, this is what the Adapter JS-impl code looks like:
function add2(a) {
return {
result: com.ibm.us.roberso.Calculator.add2(a)
};
The javascript code in the client application calling the above adapter. Note that I have a function to test passing the javascript object as a parameter to the adapter framework. See the invocationData.parameters below:
function runAdapterCode2() {
// x+y=z
var jsonObject = { "x": 1, "y" : 2, "z" : "?" };
var invocationData = {
adapter : "CalculatorAdapter",
procedure : 'add2',
parameters : [jsonObject]
};
var options = {
onSuccess : success2,
onFailure : failure,
invocationContext : { 'action' : 'add2 test' }
};
WL.Client.invokeProcedure(invocationData, options);
}
In runAdapterCode2(), the javascript object is passed as you would pass any parameter into the adapter. When worklight tries to execute the java method it will look for a method signature of either taking an Object or ScriptableObject (not a NativeObject). I used the java reflection api to verify the class and hierarchy being passed in. Using the static methods on ScriptableObject you can query and modify the value in the object. At the end of the method, you can have it return a Scriptable object. Doing this will give you a javascript object back in the invocationResults.result field. Below is the java code supporting this. Please note that a good chunk of the code is there as part of the investigation on what object type is really being passed. At the bottom of the method are the few lines really needed to work with the javascript object.
#SuppressWarnings({ "unused", "rawtypes" })
public static ScriptableObject add2(ScriptableObject obj) {
// code to determine object class being passed in and its heirarchy
String result = "";
Class objClass = obj.getClass();
result = "objClass = " + objClass.getName() + "\r\n";
result += "implements=";
Class[] interfaces = objClass.getInterfaces();
for (Class classInterface : interfaces) {
result += " " + classInterface.getName() ;
}
result += "\r\nsuperclasses=";
Class superClass = objClass.getSuperclass();
while(superClass != null) {
result += " " + superClass.getName();
superClass = superClass.getSuperclass();
}
// actual code working with the javascript object
String a = (String) ScriptableObject.getProperty((ScriptableObject)obj, "z");
ScriptableObject.putProperty((ScriptableObject)obj, "z", new Long(3));
return obj;
}
Note that for javascript object, a numeric value is a Long and not int. Strings are still Strings.
Summary
There are two ways to pass in a javascript object that I've found so far.
Convert to a string in javascript, pass string to java, and have it reconstitute into a JSONObject.
Pass the javascript object and use the ScriptableObject classes to manipulate on the java side.