phpunit-mink-trait | minimal integration layer for using Mink | Unit Testing library
kandi X-RAY | phpunit-mink-trait Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
phpunit-mink-trait Key Features
phpunit-mink-trait Examples and Code Snippets
Trending Discussions on Unit Testing
Trending Discussions on Unit Testing
QUESTION
I am using RavenTestDriver
for my .net core unit tests . Here is my configuration of my RavenTestDriver
in my unit test solution :
public class TestHostBuilder : RavenTestDriver, IAsyncLifetime
{
public async Task InitializeAsync()
{
ConfigureServer(new TestServerOptions
{
CommandLineArgs = new System.Collections.Generic.List { "--RunInMemory=true", },
FrameworkVersion = null,
});
var hostBuilder = easy.api.Program.CreateHostBuilder(new string[0])
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder.UseTestServer();
})
.ConfigureServices(services =>
{
services.AddScoped();
services.AddRavenDbAsyncSession(GetDocumentStore());
services.AddScoped((c) =>
{
return GetDocumentStore().OpenAsyncSession(new SessionOptions()
{
Database="test-server"
});
});
});
var host = hostBuilder.Start();
}
}
But when I call my Repository to get the object I get this error :
Database 'test-server' does not exist.'
at Raven.Client.Exceptions.Database.DatabaseDoesNotExistException.Throw(String databaseName) in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Exceptions\Database\DatabaseDoesNotExistException.cs:line 35
at Raven.Client.Http.RequestExecutor.d__114`1.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 883
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Raven.Client.Http.RequestExecutor.d__114`1.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 900
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Client.Http.RequestExecutor.d__101.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 455
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at Raven.Client.Http.RequestExecutor.d__109.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 678
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Client.Http.RequestExecutor.d__107.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 613
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Client.Http.RequestExecutor.d__106`1.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 583
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Client.Documents.Session.AsyncDocumentSession.d__51`1.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Documents\Session\AsyncDocumentSession.Load.cs:line 30
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at infrastructure.Persistence.RavenDb.RavenRepository`1.d__6.MoveNext() in D:\gitProjects\Orbis\infrastructure\Persistence\RavenDb\RavenRepository.cs:line 83
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at infrastructure.ApplicationCache.CacheableRepository`1.d__8.MoveNext() in D:\gitProjects\Orbis\infrastructure\ApplicationCache\CacheableRepository.cs:line 48
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at easy.api.Application.Setting.Queries.GetClientAppSettingQueryHandler.d__4.MoveNext() in D:\gitProjects\**\***\Application\Setting\Queries\GetClientAppSettingQuery.cs:line 35
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at api.common.Behaviors.UnhandledExceptionBehaviour`2.d__2.MoveNext() in D:\gitProjects\**\api.common\Behaviors\UnhandledExceptionBehaviour.cs:line 22
ANSWER
Answered 2022-Apr-05 at 07:53You need to create the database before calling OpenAsyncSession
https://ravendb.net/docs/article-page/5.3/csharp/client-api/operations/server-wide/create-database#example
QUESTION
I have an issue where I want to change what a class method returns for a single test while testing a different module. I have the following:
testingModule.test.js
const { testingModuleMethod } = require('../testingModule')
jest.mock('../helperClass', () =>
jest.fn().mockImplementation(() => ({
helperClassMethod: jest.fn()
}))
);
describe('testingModule.js', () => {
describe('testingModuleMethod', () => {
describe('when errors', () => {
const consoleSpy = jest.spyOn(console, 'error');
// SOMETHING NEEDS TO GO HERE TO CHANGE THE jest.mock ON LINE 3
await expect(testingModuleMethod(data)).rejects.toThrow('Error');
expect(consoleSpy).toHaveBeenCalled();
consoleSpy.mockRestore();
});
});
});
testingModule.js
const HelperClass = require('./helperClass');
const testingModuleMethod = async (data, callback) => {
try {
const objectToEvaluate = data.object;
const helperClassInstance = new HelperClass();
await helperClassInstance.helperClassMethod(objectToEvaluate);
log('info', "Success!");
callback(null, {});
} catch(error) {
log('error', 'Something went wrong')
}
};
No matter what I put in there I either get an error with the code (undefined) or it just ignores it and resolves due to the mock at the start. I have tried adding a spy as well as importing the class and using the prototype override.
I'm using node and "jest": "^27.0.6"
ANSWER
Answered 2022-Mar-24 at 14:16I have managed to answer this by doing the following:
Firstly I discovered that to mock a class like that I have to add a jest function into the mock like so:
describe('testingModuleMethod', () => {
describe('when errors', () => {
const consoleSpy = jest.spyOn(console, 'error');
HelperClass.mockImplementation(() => ({
helperClassMethod: jest.fn(() => { throw new Error('Error') })
}));
await expect(testingModuleMethod(data)).rejects.toThrow('Error');
expect(consoleSpy).toHaveBeenCalled();
consoleSpy.mockRestore();
});
});
This also had a knock on effect to the rest of the tests though so I added a beforeEach at the start that looks like:
HelperClass.mockImplementation(
jest.fn().mockImplementation(() => ({
helperClassMethod: jest.fn()
}))
);
Finally I needed to require the class. The overall test looks like this now and works:
const { testingModuleMethod } = require('../testingModule');
const HelperClass = require('./helperClass');
jest.mock('../helperClass', () =>
jest.fn().mockImplementation(() => ({
helperClassMethod: jest.fn()
}))
);
describe('testingModule.js', () => {
beforeEach(() => {
HelperClass.mockImplementation(
jest.fn().mockImplementation(() => ({
helperClassMethod: jest.fn()
}))
);
});
describe('testingModuleMethod', () => {
describe('when errors', () => {
const consoleSpy = jest.spyOn(console, 'error');
HelperClass.mockImplementation(() => ({
helperClassMethod: jest.fn(() => { throw new Error('Error') })
}));
await expect(testingModuleMethod(data)).rejects.toThrow('Error');
expect(consoleSpy).toHaveBeenCalled();
consoleSpy.mockRestore();
});
});
});
QUESTION
I’m using Mockito for unit testing and I want to skip the execution of a method.
I referred to this ticket Skip execution of a line using Mockito. Here, I assume doSomeTask() and createLink() methods are in different classes. But in my case, both the methods are in the same class (ActualClass.java).
//Actual Class
public class ActualClass{
//The method being tested
public void method(){
//some business logic
validate(param1, param2);
//some business logic
}
public void validate(arg1, arg2){
//do something
}
}
//Test class
public class ActualClassTest{
@InjectMocks
private ActualClass actualClassMock;
@Test
public void test_method(){
ActualClass actualClass = new ActualClass();
ActualClass spyActualClass = Mockito.spy(actualClass);
// validate method creates a null pointer exception, due to some real time data fetch from elastic
doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
actualClassMock.method();
}
}
Since there arises a null pointer exception when the validate method is executed, I’m trying to skip the method call by spying the ActualClass object as stated in the ticket I mentioned above. Still, the issue is not resolve. The validate method gets executed and creates a null pointer exception due to which the actual test method cannot be covered.
So, how do I skip the execution of the validate() method that is within the same class.
ANSWER
Answered 2022-Mar-04 at 09:36You must always use your spy class when calling method()
.
@Test
public void test_method(){
ActualClass spyActualClass = Mockito.spy(actualClassMock);
doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
spyActualClass.method();
}
In practice, instead of
actualClassMock.method();
you must use
spyActualClass.method();
QUESTION
I'm trying to create a simple test with nestjs, and I'm get this error
Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.
Returned value: Promise {}
The unit test is so simple, but I get an error when I use done();
it('throws an error if user signs up with email that is in use', async (done) => {
fakeUsersService.find = () => Promise.resolve([{ id: 1, email: 'a', password: '1' } as User]);
try {
await service.signup('asdf@asdf.com', 'asdf');
} catch (err) {
done();
}
});
ANSWER
Answered 2022-Jan-27 at 21:11You are combining Async/Await and Done.
Either use asnyc/await, or done.
it('throws an error if user signs up with email that is in use', async () => {
try {
await service();
expect(...);
} catch (err) {
}
});
or use the done format
it('throws an error if user signs up with email that is in use', (done) => {
...
service()
.then( ...) {}
.catch( ...) {}
}
done();
});
QUESTION
I am upgrading my C#
function app from .net 3.1 to 6.0`.
When I run my test cases, I found that, 1 of my test case failed with the below error.
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: System.Net.HttpWebRequest. Could not find a parameterless constructor.
Basically, I am trying to mock HttpWebRequest and below is my piece of code for that.
var httpWebRequest = new Mock();
It is working fine in .Net 3.1. I am using Moq version 4.16.1 in both the projects.
ANSWER
Answered 2022-Feb-23 at 10:53Both HttpWebRequest constructors are obsolete and should not be used. You have to use the static function "Create" to create a new instance of the HttpWebRequest class:
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
To solve your issue, use the HttpClient class instead. This class has a parameterless constructor.
QUESTION
Hi i am trying to get code coverage with .net5 in azure pipeline.
Run tests (not entire file)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
Results File: /home/vsts/work/_temp/_fv-az43-964_2021-08-25_08_31_59.trx
Attachments:
/home/vsts/work/_temp/f5dd5e9f-e260-437d-80ef-4fb917215b09/coverage.cobertura.xml
Passed! - Failed: 0, Passed: 16, Skipped: 0, Total: 16, Duration: 732 ms - /home/vsts/work/1/s/sda2021_webapi/Test/sda2021_api.tests/bin/Release/net5.0/sda2021_webapi.tests.dll (net5.0)
Result Attachments will be stored in LogStore
Run Attachments will be stored in LogStore
Info: Azure Pipelines hosted agents have been updated and now contain .Net 5.x SDK/Runtime along with the older .Net Core version which are currently lts. Unless you have locked down a SDK version for your project(s), 5.x SDK might be picked up which might have breaking behavior as compared to previous versions. You can learn more about the breaking changes here: https://docs.microsoft.com/en-us/dotnet/core/tools/ and https://docs.microsoft.com/en-us/dotnet/core/compatibility/ . To learn about more such changes and troubleshoot, refer here: https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/build/dotnet-core-cli?view=azure-devops#troubleshooting
Async Command Start: Publish test results
Publishing test results to test run '5152'.
TestResults To Publish 16, Test run id:5152
Test results publishing 16, remaining: 0. Test run id: 5152
Published Test Run : https://dev.azure.com/sda-shs/Bratislava2021/_TestManagement/Runs?runId=5152&_a=runCharts
Async Command End: Publish test results
Finishing: Dotnet run tests
Publish tests(not entire file)
##[warning]Multiple file or directory matches were found. Using the first match: /home/vsts/work/_temp/_fv-az43-964_2021-08-25_08_31_59/In/fv-az43-964/coverage.cobertura.xml
/opt/hostedtoolcache/dotnet/dotnet /home/vsts/work/_tasks/PublishCodeCoverageResults_2a7ebc54-c13e-490e-81a5-d7561ab7cd97/1.189.0/netcoreapp2.0/ReportGenerator.dll -reports:/home/vsts/work/_temp/**/coverage.cobertura.xml -targetdir:/home/vsts/work/_temp/cchtml -reporttypes:HtmlInline_AzurePipelines
2021-08-25T08:32:03: Arguments
2021-08-25T08:32:03: -reports:/home/vsts/work/_temp/**/coverage.cobertura.xml
And of course my pipeline
task: DotNetCoreCLI@2
displayName: Dotnet run tests
inputs:
command: "test"
projects: "**/xxxxx/*.tests.csproj"
arguments: '--configuration Release /p:CoverletOutputFormat=cobertura --collect:"XPlat Code Coverage" --no-build'
testRunTitle: "xxxx"
- task: PublishCodeCoverageResults@1
displayName: "publish coverage results"
inputs:
codeCoverageTool: "Cobertura"
summaryFileLocation: "$(Agent.TempDirectory)/**/coverage.cobertura.xml"
Why is more then one XML generated? I am basically balancing between no XML and more XML. I am just unable to generate one XML. (on my localhost it generates only one) Thanks for any tips.
ANSWER
Answered 2021-Aug-25 at 08:52Please replace your PublishCodeCoverageResults
with following steps:
- task: reportgenerator@4
displayName: 'Merge code coverage reports'
inputs:
reports: '$(Agent.TempDirectory)/**/coverage.cobertura.xml'
targetdir: '$(Pipeline.Workspace)/coverlet'
reporttypes: 'Cobertura'
verbosity: 'Verbose'
- task: PublishCodeCoverageResults@1
displayName: 'Publish code coverage results'
inputs:
codeCoverageTool: Cobertura
summaryFileLocation: '$(Pipeline.Workspace)/coverlet/Cobertura.xml'
And you have multiple files, because probably you have more than one test project.
QUESTION
I was fiddling with top-level statements as the entry point for a simple console app, since the new .NET 6 template use them as a default.
Yet, as the language specification very clearly states:
Note that the names "Program" and "Main" are used only for illustrations purposes, actual names used by compiler are implementation dependent and neither the type, nor the method can be referenced by name from source code.
So, if I can't reference the implicit Program
class and it's Main()
method, would it be possible to write unit tests to check the execution flow of the top-level statements themselves? If so, how?
ANSWER
Answered 2022-Feb-10 at 13:00Yes. One option (since .NET 6) is to make the tested project's internals visible to the test project for example by adding next property to csproj:
And then the Program
class generated for top-level statement should be visible to the test project and you can run it next way:
var entryPoint = typeof(Program).Assembly.EntryPoint!;
entryPoint.Invoke(null, new object[] { Array.Empty() });
Something like this is used internally to perform integration tests for ASP.NET Core 6 with minimal hosting model.
Note that generated Main
method can return task if you are using await
's in your top-level statement, so you possibly will need to capture the return of entryPoint.Invoke
and test if it is a Task
and await
it.
Another approach is to explicitly declare Program
class as partial (for example at the end of top-level statement and use it in testing project):
// ...
// your top-level statements
public partial class Program { }
QUESTION
new keyword in C++ will throw an exception if insufficient memory but below code trying to return "NO_MEMORY" when new failed. This is bad because it will raise std::bad_alloc exception .
I am writing a unit test(gtest). How to create a scenario to catch this problem.
class base{
public: base(){
std::cout<<"base\n";
}
};
std::string getInstance(base** obj){
base *bObject = new base();
*obj = bObject; //updated
return (NULL == bObject) ? "NO_MEMORY" : "SUCCESS"; // here is problem if new fail it raise an exception. How to write unit test to catch this?
}
int main()
{
base *base_obj;
getInstance(&base_obj);
}
ANSWER
Answered 2022-Jan-31 at 14:36First I think you need to catch the exception otherwise your program will never reach the point of returning NO_MEMORY
:
std::string getInstance(base **obj) {
try {
if (!obj)
throw std::invalid_argument("");
*obj = new base();
return "SUCCESS";
}
catch (const std::bad_alloc& e) {
return "NO_MEMORY";
}
catch (...) {
return "UNDEFINED_ERROR";
}
}
A quick and dirty way for testing this would be to make the constructor (or an overloaded new
) to throw std::bad_alloc
:
#ifdef UNIT_TESTING
// simulate there is no memory
base::base() { throw std::bad_alloc; }
#else
base::base() { }
#endif
But I guess the proper way would be to use something like mockcpp
Edit: Since your are using gtest
you might prefer using Google Mock to mock base
with a constructor throwing bad_alloc
instead of the dirty substitution of base::base
QUESTION
To manually send a GET request with a header, I do this with curl
:
curl http://example.com/endpoint -H "Key: Value"
I want to write a unit test that makes a request (using django.test.RequestFactory
) containing a header. How can I add a header to the request?
For clarity, below is an example of what I'd like to be able to do, though what I have written below is not valid code because RequestFactory.get()
does not have a headers
parameter:
from django.test import TestCase, RequestFactory
class TestClassForMyDjangoApp(TestCase):
def test_for_my_app(self):
factory = RequestFactory()
my_header = dict(key=value, another_key=another_value)
factory.get('/endpoint/', headers=my_header)
ANSWER
Answered 2021-Aug-10 at 15:27You need to pass HTTP_*
kwargs to the get(...)
( or any valid http methods) to pass a custom HTTP header in the request.
class TestClassForMyDjangoApp(TestCase):
def test_for_my_app(self):
factory = RequestFactory()
my_header = {"HTTP_CUSTOM_KEY": "VALUE"}
request = factory.get("/some/url/", **my_header)
print(request.headers) # {'Custom-Key': 'VALUE'}
QUESTION
I'm trying to add unit testing on a brand new strapi application. The official documentation is still in progress. So, until the documentation is being ready is there a way to add jest unit testing to strapi application ? i followed the approach in the v3 documentation with no luck.
ANSWER
Answered 2022-Jan-25 at 19:26There are quite a few changes from Strapi V3 to Strapi V4 when it comes to initializing a Strapi application's APIs. The most important changes are how Strapi populates the KOA routes, and how to make requests to the http server.
To populate the KOA routes use
await instance.server.mount();
instead of
await instance.app
.use(instance.router.routes()) // populate KOA routes
.use(instance.router.allowedMethods()); // populate KOA methods
instance.server = http.createServer(instance.app.callback());
To call the http server use
strapi.server.httpServer
instead of
strapi.server
You also need to use the new database configuration schema when defining your test database. You can use the following as an initial setup for your tests.
The following is an updated (and WIP) guide based on Strapi V3 Unit Testing guide.First run
yarn add --dev jest supertest sqlite3
or
npm install --save-dev jest supertest sqlite3
Then add the following to your ./package.json scripts:
"scripts": {
// ...strapi scripts
"test": "jest --forceExit --detectOpenHandles", //add
"watch": "yarn test --watch", // optional
}
Then add the following files:
./jest.config.js
module.exports = {
verbose: true,
testPathIgnorePatterns: [
"/node_modules/",
".tmp",
".cache"
],
modulePaths: [
"/node_modules/",
],
testEnvironment: "node",
};
./config/env/test/database.json
{
"connection": {
"client": "sqlite",
"connection": {
"filename": ".tmp/test.db"
},
"useNullAsDefault": true,
"pool": {
"min": 0,
"max": 1
}
}
}
./tests/helpers/strapi.js
const Strapi = require("@strapi/strapi");
const fs = require("fs");
let instance;
async function setupStrapi() {
if (!instance) {
await Strapi().load();
instance = strapi;
await instance.server.mount();
}
return instance;
}
async function cleanupStrapi() {
const dbSettings = strapi.config.get("database.connection");
const tmpDbFile = dbSettings.connection.filename
//close server to release the db-file
await strapi.server.httpServer.close();
//delete test database after all tests
if (dbSettings && tmpDbFile) {
if (fs.existsSync(tmpDbFile)) {
fs.unlinkSync(tmpDbFile);
}
}
// close the connection to the database
await strapi.db.connection.destroy();
}
module.exports = { setupStrapi, cleanupStrapi };
Note that you need to have the /hello endpoint in your project as specified in the strapi docs for the next tests to pass.
./tests/app.test.js
const { setupStrapi, cleanupStrapi } = require("./helpers/strapi");
jest.setTimeout(15000);
beforeAll(async () => {
await setupStrapi();
});
afterAll(async () => {
await cleanupStrapi();
});
it("strapi is defined", () => {
expect(strapi).toBeDefined();
});
require('./hello')
./tests/hello/index.js
const request = require('supertest');
it('should return hello world', async () => {
await request(strapi.server.httpServer)
.get('/api/hello')
.expect(200) // Expect response http code 200
});
I hope this helps anyone struggling with the same issues. I will update the answer as I progress.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install phpunit-mink-trait
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page