dimanche 31 mars 2019

How to make Autocomplete Textview focusable in android UI automator?

Autocomplete TextView is not displayed in the UIAutomator View hierarchy. Is there any special constraint to make it focusable in UIAutomator?

Checked if the edit text is focusable

How to Write Tests For Android App For File Transfer and QR Code Confirmation B/w Two Devices

I want to write tests for an android app that transfers files b/w two devices using hotspot/QR Code. To connect those two devices a hotspot connection is required. The process works like this:

• In order to send something, Device A generates a QR Code and it's hotspot is turned on and on the same page a port no is written.

• The device on the receiving end has two ways to receive the file.

1) It should connect to Device A's hotspot. After that it will have to write the port no that was shown on Device A's screen with the hotspot.

2) It should scan the QR Code that is shown on Device A's screen.

These tests should work on emulator because I can't physically own all Android version devices.

I need to write tests for this app's functionality.

1- To confirm QR Code has been generate and then verified.

2- To confirm files are transferred/received successfully.

3- To confirm the hotspot service

Here's the app documentation to read more about it. GIFs are also available showing how this app works.

What is the way to write tests against a 3rd party software like redis

I'm not sure if this is the right forum to ask this question if not kindly point me in the right direction.

I wanted to create a library/client for a 3rd party tool, which is similar to redis. And for the unit/integration tests, I see that in predis library, they have tests which directly interacts with a running redis instance and there are tests which make use of mocks.

So my question is that, is it okay if I write tests running against an actual instance of the 3rd party tool or should I employ mocks all the way?

why is the remaining number of occupants not calculated correctly?

I'm coding a rescue simulation program and while applying the required tests it keeps giving a failure saying that the number of occupants remaining in the building is not correctly calculated and I can't figure out why! below i provided the two methods that are supposed to give back the number of occupants. Thanks in advance!

public void treat(){
    boolean f=false;
    if(!f){
          ((Disaster)((Citizen)this.getTarget()).getDisaster()).setActive(false);
               ResidentialBuilding r= (ResidentialBuilding)this.getTarget();
              if(r.getOccupants().size()!=0){
                 for(int i=0;i<r.getOccupants().size();i++){
                     if(this.getPassengers().size()<=this.getMaxCapacity()){
                          f=true;
                          Citizen z=(Citizen)r.getOccupants().get(i);
                          if(z.getState()!=CitizenState.DECEASED){
                              r.getOccupants().remove(i);
                              this.getPassengers().add(z);
                          }    
                      }

                  }
              } 
              else{
                  this.setState(UnitState.IDLE);
                  this.jobsDone();
              }
          }
        else
            this.cycleStep();

        }   




    public void cycleStep(){
        if(super.getDistanceToBase()==0)
            super.getWorldListener().assignAddress(this, 0, 0);
        if(super.getTarget()!=null){
            if(this.getLocation()== this.getTarget().getLocation()){
                this.setDistanceToBase(this.getLocation().getX() + this.getLocation().getY());
            }
            else if(this.getDistanceToBase()<=0){
                this.setDistanceToBase(0);
                this.setLocation(new Address(0,0));
                for (int i = 0; i < this.getPassengers().size(); i++) {
                    Citizen c = (Citizen)this.getPassengers().remove(i);

                }
            }
            else{
                this.setDistanceToBase(this.getDistanceToBase()-this.getStepsPerCycle());
            }
        }
    }


Implement Widget testing

I'm pretty noob in testing and don't know how to implement widget testing for the following flutter code. thanks in advance.

code description: I have made a slideshow using carousal widget and a button using inkwell this button simply directs to the next screen.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

import 'package:flutter/material.dart';
import 'package:baseball/ui/phone/phone_page.dart';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/services.dart';
import './splash_widgets.dart';

class SplashPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,
    ]);
    return Container(
      child: Scaffold(
        appBar:PreferredSize(
        preferredSize: Size.fromHeight(60.0),
    child: Appbar()),
        body: Center(
          child: Column(
            children: <Widget>[
              Expanded(
      child: Carousel(
        images: [
          AssetImage('images/SlideImage_1.jpg'),
          AssetImage('images/SlideImage_2.jpg'),
          AssetImage('images/SlideImage_3.jpg'),
        ],
        animationCurve: Curves.fastOutSlowIn,
        animationDuration: Duration(milliseconds: 2000),
      ),
    ),
              SizedBox(
      height: 70,

      width: double.infinity,
      // height: double.infinity,
      child: InkWell(
        onTap: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => Phone()),
            ),
        child: new Container(
          //width: 100.0,
          height: 50.0,
          decoration: new BoxDecoration(
            color: Theme.of(context).buttonColor,
          ),
          child: new Center(
            child: new Text(
              'GET STARTED',
              style: Theme.of(context).textTheme.button,
            ),
          ),
        ),
      ),
    )
            ],
          ),
        ),
      ),
    );
  }
}```





How to pass Session Attributes to Lex Bot from Botium Client?

I need to pass "Session Attributes" from botium to Lex Bot - how can i do it ? Am using container mode as "lex", when i run the convos i get "BadRequestException: Invalid Bot Configuration: No usable messages given the current slot and sessionAttribute set." Please help !

How do you add Src/Test Folder to Coverage Report in Eclipse?

I am setting up a j-unit 5 test class under src/test/java folder and set up a coverage report for my project. My coverage report is only returning the src/main class and not the test class. How can I add my test class file to also be included in the coverage report?

Results Here

How to mock the baseUrl and sendredirect

I wrote this function, and I'm trying to write the jUnit Tests of this function. The first test runs, but the second one have some problems. Can you please help me?

This is the function

@GetMapping(value = "/productdetail/{productId}.pdf")
public void getProductDetailPdf(@PathVariable("productId") final String pProductId,
        final HttpServletResponse pResponse, final HttpServletRequest pRequest) throws Exception {
    final String pdfFileName = pProductId + ".pdf";
    pResponse.setContentType("application/pdf; charset=UTF-8");
    pResponse.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
    final String html = jsonProductDetailPdfFacade.showJsonProductDetailPdf(SessionUtil.get(pRequest), pProductId);
    if (!html.equals(EMPTY)) {
        pdfConverterFacade.htmlToPdf(html, pResponse);
    } else {
        final String url = pRequest.getRequestURL().toString();
        final String baseURL = url.substring(0, url.length() - pRequest.getRequestURI().length());
        final String redirect404 = baseURL + _404;
        pResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        pResponse.sendRedirect(redirect404);
    }
}

This are the tests:

private static final String MIDDLE_URL = "middleUrl";
private static final String ANY_URL = "anyUrl";
private static final String _404 = "/404";
private static final String EMPTY_STRING = "";
private final static String ANY_PRODUCT_ID = "anyProductId";
private final static String ANY_HTML = "anyHtml";
private final static String EMPTY = EMPTY_STRING;
private final PdfConverterFacade pdfConverterFacade = mock(PdfConverterFacade.class);
private final JsonProductDetailPdfFacade jsonProductDetailPdfFacade = mock(JsonProductDetailPdfFacade.class);

private final PdfConverterController controller = new PdfConverterController(pdfConverterFacade,
        jsonProductDetailPdfFacade);

@Test
public void productDetailAsPdf() throws Exception {
    final HttpServletResponse response = mock(HttpServletResponse.class);
    final HttpServletRequest request = mock(HttpServletRequest.class);
    final SessionUtil sessionUtil = mock(SessionUtil.class);
    when(response.getContentType()).thenReturn("application/pdf; charset=UTF-8");
    when(SessionUtil.get(request)).thenReturn(sessionUtil);
    when(jsonProductDetailPdfFacade.showJsonProductDetailPdf(sessionUtil, ANY_PRODUCT_ID)).thenReturn(ANY_HTML);
    controller.getProductDetailPdf(ANY_PRODUCT_ID, response, request);
    verify(pdfConverterFacade).htmlToPdf(ANY_HTML, response);
}

@Test
public void productNotFound()throws Exception{
    final HttpServletResponse response = mock(HttpServletResponse.class);
    final HttpServletRequest request = mock(HttpServletRequest.class);
    final SessionUtil sessionUtil = mock(SessionUtil.class);
    when(request.getRequestURL().toString()).thenReturn(ANY_URL);
    when(ANY_URL.substring(0, ANY_URL.length() - request.getRequestURI().length())).thenReturn(MIDDLE_URL);
    when(SessionUtil.get(request)).thenReturn(sessionUtil);
    when(jsonProductDetailPdfFacade.showJsonProductDetailPdf(sessionUtil, ANY_PRODUCT_ID)).thenReturn(EMPTY_STRING);
    when(response.getStatus()).thenReturn(404);
    verify(response).sendRedirect(MIDDLE_URL + _404);
}

So the first tests works. the second one doesn't run. This is the else part of the function.

Can you please tell me what's wrong?

HashMap put method doesn't add data

I'm trying to compare two HashMaps while retrieving the data from a database with sql query(JUnit Test). I get the data perfectly from the database but for some reason one of the HashMap stay empty.

I have checked that the query is working and indeed getting the data I need and tried to use ArrayList and a simple array to store the data, which both of them works.

@Autowired
EntityManager em;

@Test
public void totalScore() {

    //First query
    String qs = "select driver.id, n_safety_events from driver join "
            + "trips_matches on driver.id=trips_matches.driver_id join "
            + "trips on trips.id=trips_matches.trip_id ";

    //Second query
    String qs2 = "SELECT daily_driver_scores.driver_id, daily_driver_scores.n_events FROM daily_driver_scores";


    //Get the data from the database to List
    Query getExpectedResultQuery = em.createNativeQuery(qs);
    Query getActualResultQuery = em.createNativeQuery(qs2);

    List<Object[]> expectedResultList = getExpectedResultQuery.getResultList();

    List<Object[]> actualResultList = getActualResultQuery.getResultList();

    HashMap<Integer, Integer> expectedResult = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> actualResult = new HashMap<Integer, Integer>();

    //Work properly 
    for (Object[] item : expectedResultList) {
        try {
            int driverId = Integer.parseInt(item[0].toString());
            int numberOfSafetyEvents = Integer.parseInt(item[1].toString());

            //If the key is already exits add to his value, else just put the value
            expectedResult.put(driverId,
                    expectedResult.containsKey(driverId) ? expectedResult.get(driverId) + numberOfSafetyEvents
                            : numberOfSafetyEvents);

        } catch (Exception e) {
            // log.error(e.getMessage(), e);
        }
    }

    //Exactly same as the expected but dosen't work
    for (Object[] item : actualResultList) {
        try {

            int driverId = Integer.parseInt(item[0].toString());
            int numberOfSafetyEvents = Integer.parseInt(item[1].toString());

            actualResult.put(driverId,
                    actualResult.containsKey(driverId) ? actualResult.get(driverId) + numberOfSafetyEvents
                            : numberOfSafetyEvents);

        } catch (Exception e) {
            // log.error(e.getMessage(), e);
        }
    }

    assertEquals(actualResult, expectedResult);
}

So in the second for (the actual result) I get the data (driverId and numberOfSafetyEvents isn't 0 or null) but when I use the put nothing happend. I have used debugger mode to see if some value are overwritten in the hashmap but for the whole time the actualResult HashMap staying the same.

Am I doing something wrong? because to me the first for and the second for is the same.

Writing a computer program that will analyse the quality of another computer program?

I'm interested in knowing the possibilities of this. I'm working on a project that validates the skills of a software engineer, currently we validate skills based on code reviews by credentialed developers.

I know the answer if far more completed that the question, I couldn't imagine how complex the program would have to be able to analyse complex code but I am starting with basic programming interview questions.

For example, the classic FizzBuzz question:

Write a program that prints the numbers from 1 to 20. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

and below is the solution in python:

for num in range(1,21):
    string = ""
    if num % 3 == 0:
        string = string + "Fizz"
    if num % 5 == 0:
        string = string + "Buzz"
    if num % 5 != 0 and num % 3 != 0:
        string = string + str(num)
    print(string)

Question is, can we programatically analyse the validity of this solution?

I would like to know if anyone has attempted this, and if there are current implementations I can take a look at. Also if anyone has used z3, and if it is something I can use to solve this problem.

Including private headers in tests

I have the following CMake project structure:

mylib
 |
 |_include
 |    |_mylib.h
 |
 |_src
 |  |_linux
 |      |_internal1.h
 |      |
 |      |_internal1.cc
 |      |
 |      |_internal2.h
 |      |
 |      |_internal2.cc
 |      |
 |      |_mylib.c
 |_test
 |   |_all_tests.cc
 |
 |_CMakeLists.txt

My CMakeLists.txt looks as follows:

cmake_minimum_required(VERSION 3.0)

project(mylib)

SET(LIB_SOURCES
    src/linux/internal1.cc
    src/linux/internal2.cc
)

SET(LIB_TEST_SOURCES
    test/all_tests.c
)

add_library(mylib SHARED ${LIB_SOURCES})
target_include_directories(mylib PUBLIC ${PROJECT_SOURCE_DIR}/include)

add_executable(all_tests ${LIB_TEST_SOURCES})
target_include_directories(all_tests PRIVATE src/linux) # <-- HERE?
target_link_libraries(all_tests mylib)

enable_testing()
add_test(NAME all_tests COMMAND all_tests)

The problem: I want to test functions that are not in the
target_include_directories(mylib PUBLIC ${PROJECT_SOURCE_DIR}/include). In my case they are functions defined in internal1.cc and internal2.cc.

Adding target_link_libraries(all_tests mylib) does not add the private headers in the include directory. So the only solution I found currently is to add to include path the whole src/linux directory.

I'm not sure about this approach since it adds h-files as well as c-files.

Is there a better solution for such a case?

assert every selected div element

I want to test every selected div, but it only test the first select element.

This is DOM:

<div>
    <div>
        <div>
            <div class="select" [datetime="20190101"]>
                
            </div>
        </div>
    </div>

    <div>
        <div>
            <div class="select" [datetime="20190102"]>
                
            </div>
        </div>
    </div>

    <!-- and many of them -->
</div>

This is my testing:

/** @test */
public function every_data_should_match()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('/page');

        $browser->whenAvailable('div.select', function ($div) {
            $datetime = $div->attribute('', 'datetime');
            $expected_data = User::where('datetime', $datetime)->first()->data;

            $data = $div->getAttribute('outerHTML');

            $this->assertSame($expected_data, $data);
        }
    }
}

There should have many assertions, but there is only one, how to fix so the testing would iterate every div.select?

Each .select belongs to different parent, so I couldn't use .select:nth-child(n).

Strategy for test pipeline with .NetCore and KAFKA

After having set up a cloud service prototype based on Kafka and .NetCore applications (webapi as producer and console as consumers), I am designing the profile of my continuous integration and testing environment. Starting from scratch, I am interested to not reinvent the wheel, and use state-of-the-art tools for that. What are the major pre-requesite I have to work with? I speaking about tools, frameworks...

I use open-source applications, so Jenkins sounds like a "must use". But how to deal with the global environment? Do I need to have a always running kafka cluster to support continous testing jobs?

My thoughts were at this stage:

  • Always running KAFKA and DB
  • jobs

    • installing a test DataSet test DB
    • checking out the latest consumer component to test
    • building the related package into docker
    • starting the docker image in the test environment
    • starting producer/consumer test scripts (I would have run python? other best way to do?) to make the component under test live and verify it does the job, measuring performances and so on...

Am I missing something here? Is there any better way to do? Is there another way to test consumer/producer IO without a running Kafka cluster?

Thanks,

Unable to new object returned from proxyquire

I am trying to test an object using proxyquire. The object is a simple JavaScript / TypeScript class with some dependencies. I am using proxyquire with sinon to override those dependencies and that's working fine. but I can't create new instance of the class to run it's methods on the test program.

I have tried to to create a static method on the class which returns new instance but the error is "Proxy.create is not a function"

// a stub of one of the dependents in 
const poolRepositoryStub = {
  insert: _.constant({}),
  '@noCallThru': true,
};

const Proxy = proxyquire('../../dist/src/components/proxy.js', {
  '../repository/pool-repository': poolRepositoryStub,
  '@noCallThru': true,
});

describe('Test ReportCheckComponent', () => {
  before(() => {   
    // this one failed say Proxy is not a constructor
    new Proxy()

    // and this one also failed on Proxy.create is not a function
    Proxy.create();
  });

  it('report-check.spec.ts: test run method using sinon stub', () => {        

    sinon
      .stub(poolRepositoryStub, 'insert')
      .returns(Promise.resolve(null))

    // ... the rest of the test code


  });
});

Design pattern for Cucumber assertions partially matching messages

I am trying to write a component testing framework for an application. This application can send messages through JMS/Websockets (the transport isn't important). I'm using cucumber to define my BDD steps.

After an action has been performed a number of events will have been sent to the component testing server for matching against the expected list.

I'm looking for a design pattern/approach that will give me the flexibility to write different named fields in the data table for the same message type without having the code behind them being bloated by boilerplate for each specific field.

Example, given a message with the following definition:

Order {
  String orderId;
  int size;
  int amount;
  String name;
}

I want to be able to write different assertions:

Then I should have received following orders:
|orderId|size|amount|
|order1 | 10 | 50   |
|order2 | 5  | 10   |

Then I should have received following orders:
|orderId|name |
|order1 |ted  |
|order2 |steve|

A couple of ways I have thought of for performing this type of validation:

1) Loop through the received messages, filter out all order messages. Then for each named field define a lookup function on that given an order message will return the value for that field. Check equality for all fields on each received message.

This approach will leave a lot of boiler plate code because you have to define specific lookup functions for each value in the message (these messages can have 100 fields)

2) Create an Order POJO. Parse the received messages into an Order POJO. Also parse the fields defined in the assertion into the POJO. In the equals method do something like 'if field is set from assertion, then include it in equality check, else exclude it'.

This feels better but might have problems when message has a list type. Ie should the list be null, or empty list? Can we have lists of ignored values with certain size?

There must be documentation/design patterns around this but I can't find any good examples. Any pointers in the right direction would be appreciated

samedi 30 mars 2019

Spek2 generate XML report that includes Scenario and Feature level information for Jenkins/Surefire

I have made behavior tests in Spek2/Kotlin which are working very nicely.

To run these on Jenkins with surefire and maven I use a series of commands like:

mvn clean
mvn surefire-report:report
mvn site

My intention is to create a nice HTML page to see the test results which show the class, the Feature, The Scenario and then the test steps (Given, Then, etc)

However what I get is a report showing the Class then directly listing out the Given, then, etc steps with no reference to the Feature or Scenario anywhere on the page.

Surely this is possible to do but I have been battling with it for days now to no avail!

Print files and directories using if-then-else and state whether or not it's a file or directory

Create an if-then-else statement to test if a file, represented by the variable $filename, is in fact a file. The statement should also output a notification message which indicates the result of the test.

My goal is to incorporate the above, but by listing the contents of the current directory only and next to each line it states if it's a file or directory [maybe in color].

So far I have gotten this to work.

filename="wp-config.php"

if [ -f "${filename}" ] ; then echo "${filename} is a file" elif [ -d "${filename}" ] ; then echo "${filename} is a directory" fi

How to fix "not ok timeout!" when testing fastify route?

I am trying to test fastify route with tap. Here is the test file:

const tap = require('tap')
const buildFastify = require('../../src/app')

tap.test('GET `/` route', t => {
    t.plan(4)

    const fastify = buildFastify()

    // At the end of your tests it is highly recommended to call `.close()`
    // to ensure that all connections to external services get closed.
    t.tearDown(() => {
        fastify.close();
    });

    fastify.inject({
        method: 'GET',
        url: '/'
    }, async (err, response) => {
        t.error(err)
        t.strictEqual(response.statusCode, 200)
        t.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
        t.deepEqual(JSON.parse(response.payload), { hello: 'world' })
        t.done()
    })
})

After running test I see in the console:

....Closing mongoose connection ...
listening on 3001
tests/routes/status.test.js ........................... 4/5 30s
  not ok timeout!

running tests with npm script: "test": "env-cmd ./test.env tap tests/routes/status.test.js"

How do i work with API testing on default nginx home page?

I have setup nginx with docker and now i would like to host a simple page which can process POST and GET responses. Basically, i would like try python API testing using python in that page.

I have a default nginx page which process POST requests. So, i was able to test that. But, i'm confused on how to POST data on that page.

Existing code to test GET calls using requests library

r = requests.get(url,headers=headers)
    assert r.status_code == 200

How to versioning/tag testframework with REST API tests against multiple Microservices?

We have a lot of different Microservices and we test amongst other things the REST APIs of these different Microservices. These automated REST API tests are not included in the Microservice projects/Repos. Instead we have a testautomation project containing all different tests, like API test and end2end tests, because we want to test everything as a black box.

Now the problem is that there are infinitely combinations of different Microservice versions are possible to test against on a test environment (example: Executing the tests today against Microservice A with version 1.0 and Microservice B with version 2.0 is different to execute the same tests tomorrow against Microservice A with version 1.1 and Microservice B with version 2.1). So, we will need some kind of versioning or tagging our testautomation project or the executed tests, that we are able to identify which combinations of different Microservice versions are valid and which combinations are not valid/working, because e.g. some tests will fail.

Are there any recommendations or experiences to implement and integrate such a versioning/tagging mechanism?

vendredi 29 mars 2019

What is Android WebView testing and its benefits for website?

I am working on a website customisation and its almost done and tested over various devices for its working and responsiveness. But my client continuously asking for test this website on Android WebView. For this I study This Article and what I understand is that WebView is used for execute webpages over android app. Correct me if I am wrong.

The website I am talking about has no android app. So please let me know

  • How do I perform Android WebView testing for this website?
  • What are Android WebView testing benefits for this website, when there is no android app using its webpages?
  • and why it is important to perform Android WebView testing for this website when users have fully functional web browser in their mobile ?

Testing the content of a flash message in Python

I would like to test whether a flash message contains certain text. So I have the line:

response = tester.post('login',
        data=dict(
        username='test', password='lol'), follow_redirects=True)
assert 'Welcome back!' in response.data

This however fails with the error message:

 assert 'Welcome back!' in response.data
 TypeError: a bytes-like object is required, not 'str'

Does anyone understand what I am doing wrong?

Create a soap ui mock project with Java

I'm working on a project where I need to mock the application backend. What I want to know is that if I can intercept the requests and responses in my project, can I write them in a xml file the same way soapui does? Does anyone have experience doing so?

I'm logging all the requests and responses to a file right now. I'm trying to figure out how soap ui stores the mock responses in xml format.

Passing request body to post using super-test

I'm testing an express server using super-test and I need to test a post call. I assume the post should be successful and return a status of 200 but it is returning 401. I've been told by someone that I need to pass a request body with the post but I'm unsure exactly how to do this.

I've attempted to use .send({name: 'aName'}) but that gives me the same 401 code.

Below is the app.js

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const hateoasLinker = require('express-hateoas-links');
const AValidator = require('./AValidator');
const BValidator = require('./BValidator');
const schema_v1 = require("./schema.json");
const {
    logService: logger
} = require("@utils");

let aValidator = AValidator(schema_v1);

let ValidatorApi = BValidator.ValidatorApi('api');
let adminValidator = BValidator.ValidatorAdmin('admin');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(hateoasLinker);

app.post('/*/activate',admiValidator, (req, res) => {
    console.log("In Activate===============>");
    res.status(200);
    res.json({
        rel: "self",
        method: "POST",
        title: 'Activate Solution',
        href: "/activate"
    });
});

Here is the app.test.js

const request = require('supertest');
const bodyParser = require('body-parser');
let AValidator = require('../src/AValidator');
let BValidator = require('../src/BValidator');
BValidator = jest.fn();
AValidator = jest.fn();
app = require('../src/app');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

describe('Test os GET/POST calls in app.js', ()=>{

  test('Tests activate post', (done)=>{

    BValidator.mockReturnValue({
      ValidatorApi: (req,res,next)=>{
        next();
      },
      ValidatorAdmin:(req,res,next)=>{
        next();
      }
    });

    AValidator.mockImplementation((schema)=>{
      return function (req,res,next){
        next();
      }
    });


    request(app)
      .post('/test/activate')
      .set({name:'josh'})
      .then((response)=>{
        expect(response.statusCode).toBe(200);
        done();
      })

  })


});

So ultimately I'd like this post to resolve successfully and return a status code of 200.

Controller testing Rspec -Unauthorized request after user login - expected the response to have a success status code (2xx) but it was 401

I got unauthorized request after user login (get request on :index). Here is a simple example of users test, I can't see what I'm doing wrong.

In controller current_user exists and is signed in, but request is unauthorized. Why is that?

module ControllerMacros

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      user = FactoryBot.create(:user, company: FactoryBot.create(:company))
      sign_in user
    end
  end

end

rspec_helper.rb:

require 'spec_helper'
require 'devise'
require 'support/controller_macros'

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.extend ControllerMacros, type: :controller
end

Users test:

require 'rails_helper'

RSpec.describe Api::V1::UsersController do
  include Devise::Test::ControllerHelpers

  describe "GET /api/v1/users" do
    login_user

    it "should get list of users" do
      get 'index'
      expect(response).to have_http_status(:success)
    end

  end
end

This tests are passing and working fine:

   it "should have a current_user" do
      expect(subject.current_user).to_not eq(nil)
    end

    it "should be signed in" do
      expect(subject.user_signed_in?).to be true
    end

How to Fix this string Connection error while connecting with other pc

I have problem, when i install my new software on any other pc. it gives me String Connection Error Meanwhile, it works on my pc very well. Please help me, Tight Deadlinesenter image description here

How to print list of failed tests at the end of test run?

What is the current behavior?

Jest spits out each error individually without any summary at the end of run about which tests failed (individual files)

What is the expected behavior?

Just like now + a helpful summary of which tests failed.

Can Katalon Studio read CAPTCHA number while running a test

I want to test login using katalon, but I use CAPTCHA. The number in CAPTCHA is always changed. Can Katalon read that while running a test?

Is automating angular7 application via selenium is good idea

We have already a robust framework in place for automating the UI as well as customized classes for various other java operation like posting api, xml handling, file handling , json handling, database operation etc . Since there is a time crunch to switching to protractor and framework development is not possible.

So working with angular7 for selenium is good option. Since we can handle all the synchronization issues via selenium

C# Shall I make my windows form event related private functions public just for testing purpose?

This might be a very generic question about how to do the unit test for windows form application and with async functions.

I am writing the unit test case for a windows form application which has the async function everywhere.

I have all the event handler functions, for example, button click event function, private. I need to test these functions but I cannot call these functions directly outside to test them.

I tried to fire the event function from the unit test code via calling PerformClick(). It works fine with generic function but does not work properly with async function as I think PeformClick() doesn't await and I cannot verify the result in the testing code.

Here is a simple example of my code. We have two-layout structures. Form class to have only the form design. Form presenter to hold all the logic of functions. I need to test the BtnApplyChangeClick function in the presenter class.

public interface IStandForm
{
    Control.ControllCollections controls {get;}
}
public partial class Form1 : Form, IStandardForm
{
   public Form1()
   {
        InitializeComponent(); // It has a button called BtnDelete
   }
   public Control.ControlCollection controls
   {
        return this.Controls;
   }
}

public class FormPresenter
{   
    IStandardForm myForm;
    IDBController dbController;
    public FormPresenter(IStandardForm form, IDBController dbController)
    {
       this.myForm = form;
       this.dbController = dbController;

       //Assign the event to the button
       Button BtnDelete= (Button)myForm.Controls["BtnDelete"];
       BtnDelete.Click += new System.EventHandler(BtnDeleteClick);
    }

    private async void BtnDeleteClick(object sender, EventArgs e)
    {
        //some validation code   

       //Call db delete
        await dbController.Delete();  
    }
}

//Test Code
[TestFixture]
public class TestFormLogin
{
    [Test]
    public async Task Delete_With_Exception()
    {            
        Mock<IDbController> mockDbController = new Mock<IDbController>();
        mockDbController.Setup(c => c.Delete()).ThrowAsync<Exception>(new Exception("Test Exception"));
        IStandardForm myForm = new Form1;

        FormPresenter = new FormPresenter(mockDbController.Object, myForm);
        Button BtnDelete=(Button)myForm.Controls["BtnDelete"];

        Action act = () => BtnDelete.PerformClick();

        //This assertion will be failed as PeformClick won't wait
        act.Should().Throw<Exception>();  
    }
}

The last line Exception assertion won't work. If I could call event handler function BtnDeleteClick the assertion will be fine.

Would that be a bad idea to just simply make the private event handler function to be public just for testing purpose? It will make my life easier but doesn't sound make sense.

With NUnit, in TearDown, how to get, whether the test was run solo?

So, in TearDown, I have got the info about the test outcome and the test result message, but I would like to handle things specifically on whether the test was run solo (a single test in the test session) or was started in a whole set of tests (e.g. "Run all tests/All tests from Solution").

How to get info about the test run/session in the TearDown method?

jeudi 28 mars 2019

Why jmeter generate other requests and put a number for them

I have a script, one of the requests in the script is: redireccion.html, but when I generate the HTML Dashboard report I see: redireccion.html-0, redireccion.html-1, redireccion.html-2

Why those requests are generated by Jmeter?

HTML Dashboard Report Graph

How do I change the synthetic voice for a section of my Action?

Trying to change the voice from female to male for one section of my Action.

I'm using the Voiceflow tool, and have uploaded my Action to Actions on Google. However, I'm not clear on how to change one section of my action from a female voice to male.

I'm looking in Dialogflow, but not seeing any place where there are tags. So maybe that's my question. Where are the speak tags in Dialogflow?

In "Fulfillment", I have the Webhook enabled, and it goes to a Voiceflow URL. However, that's just for the audio files I'm using, correct? Not the text in the tags to be spoken?

I'm wanting to have a female voice for one part of the voice app, and a male voice for the other part.

Currently, the app plays all the way through with the female voice.

Running nightmare tests in Browserstack

I recently defined some User Interface test cases using The Nightmare library.

My question is if it is possible to execute these tests in a cloud tool like saucelabs, broswerstack or device farm?

Below i have included some of the code for reference.

const Nightmare = require('nightmare')
const assert = require('assert')

describe('Landing Page', function() {
  this.timeout('30s')

  let nightmare = null
  beforeEach(() => {
    nightmare = new Nightmare({ show: true })
  })

  describe('/ (Home Page)', () => {
    it('should render landing page', done => {
      nightmare.goto('http://localhost:3000/')
        .exists('#root > div > div > div > div > div > div:nth-child(1) > a > img')
        .exists('#root > div > div > div > div > div > div:nth-child(1) > a > span > b')
        .exists('#root > div > div > div > div > div > div:nth-child(1) > a > small')
        .wait(1000)
        .click('#root > div > div > div > div > div > div:nth-child(1) > a > img')
        .wait(1000)
        .end()
        .then(function (result) { done() })
        .catch(done)
    })
  })
})

When testing actions on google, is it possible to test on a real device with a different account than created the action?

We have created an action with an email belonging to the developer.

Using the developer's account we have successfully tested in the simulator and on a Google Home Mini. See: "Testing on real hardware" https://developers.google.com/actions/dialogflow/submit

Now want to test on a real device with a different account.

In the simulator I am able to share the action with my team members for others to test before deploying. See "Sharing your project" https://developers.google.com/actions/smarthome/testing-deploying

The team members are able to access and test on the simulator, but we are having trouble getting them testing on a support device.

After sharing in the the simulator, should they be able to test on any supported devices?

What is the best practise for writing language feature unit test?

What is the best practice in writing unit test for the method when inside core .NET functions only?

I am new to unit test and I read a lot about best practices of writing unit test and they recommend not to test language features (like to ensure property returns value). My case seems to be related to native code only, but I can't 100% be sure that it is language feature and I can skip writing test. Making test for this method looks like I'm writing test for .NET library itself.

I wanted to set expected string value and compare to it, but date.ToString() is culture specific.

public static string ConvertDateToDateTimeString(this DateTime date)
{
  return new DateTimeOffset(date, TimeZoneInfo.Local.GetUtcOffset(date)).ToString("o");
}

I created simple test, but when I am trying to set expected value, I realise that it should be the same as ConvertDateToDateTimeString() implementation.

Doing this makes this unit test useless.

[TestMethod]
public void ConvertDateToDateTimeString_WhenCalled_ReturnConvertedDateTimeString()
{
  var date = new DateTime(....)

  var actual = date.ConvertDateToDateTimeString();

  string expected = ...

  Assert.AreEqual(expected, actual);
}

If I skip writing test for this than code coverage won't be full.

Could you please recommend any useful practices what to do in such cases?

Junit test for Loop

I am teaching myself Junit testing and I am struggling to create a test for the following code

 private ArrayList<AirbnbListing> List;

   public int getAvgReviews(){
    int sums = 0;
    for (int i = 0 ; i < List.size(); i++){
        AirbnbListing houses = List.get(i);
        if(houses.getPrice() >= fromValue && houses.getPrice() <= toValue){
            sums += houses.getNumberOfReviews();
        }
    }
    return (sums/getNoOfProperties());
}

Can someone help me out

Kestrel server is not accessable after IWebHost.Start

I have set of xUnit tests that have to make requests to running Kestrel servers. These tests are placed in .Net Core App project. There is a code that runs the only once before tests in the beginning and has to run Kestrel servers on the specific ports.

So I need that my servers were runned and tests were passed. For my server host I have the next code:

WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel()
.UseUrls("http://*:8000")
.UseContentRoot(Directory.GetCurrentDirectory())
.Build()

  • If I run server via IWebHost.Run then main thread is blocked and tests are not performed. But server starts and is able to get requests
  • If I run server via IWebHost.Run in the separate thread then nothing happens (there is no server port in list of ports of netstat -a)
  • I got the same effect If I use IWebHost.Start in separate thread
  • And if I use just IWebHost.Start then main thread is not blocked, there is a port in the list of ports but server doesn't respond to request from browser

Is there a way to run Kestrel server from .Net Core App test project and perform tests?

junit tests with flying saucer

I don't know hoe should I make thi unit test, can you please help me?

public void htmlToPdf(final String pHtml, final HttpServletResponse pResponse) throws IOException {
        if (pHtml != "") {
            final ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(pHtml);
            renderer.setPDFVersion(new Character(PdfWriter.VERSION_1_7));
            final ServletOutputStream out = pResponse.getOutputStream();
            try {
                renderer.layout();
                renderer.createPDF(out);
                out.flush();
                out.close();
            } catch (final DocumentException e) {
                pResponse.setStatus(500);
            } catch (final Exception e) {
                pResponse.setStatus(404);
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (final IOException e) {
                        // ignore
                    }
                }
            }
        }

I don't really know how I have to do it. I need to have 100 coverage..

JEST test suite fails if restricted to run in one core

Scenario: Frontend typescript project, using React and Redux. We have something like 800 tests spread around 150 test suites. Some of tests are unit tests, but other are actually integration tests. Ocasionally we mock backend calls, which we use to populate the Redux store. Backend calls are asynchronous in our production code, so we use async and await when we use them in tests (even if they are mocked).

Using the call

npm test

Shows that all the tests are beautiful and green. However:

numactl -C 0 npm test       # one test is red 

makes one test to fail. Adding a second CPU:

numactl -C 0,1 npm test     # all tests are green

is enough to get all tests to pass without any problem. I am trying to understand what could be causing this but I have honestly no clue. I cannot see the connection between the nunmber of CPUs at work and the succes of the tests :( Did someone ever face a similar scenario?

Additional information: if I disable the other tests in the test suite the red one belongs to, then the call numactl -C 0 npm test works fine (i.e. all tests are green).

I am aware that I am providing very little information. I will happily provide any information that you deem relevant (that may put me on the right track as well!). Any little hint will be very appreciated. Thanks!

Can't get pytest to recognize nested imports

I am trying to get pytest working on a project I am working on. I've been struggling to find the correct way to import modules into the tests. For example, I have a test_changelog.py file that imports release_all_in_one.changelog_utils but a function in that module calls a function in a different module, jira_utils.py and its failing to find that.

I have tried many different setups of how to setup tests with pytest. I tried using setup.py, different folder locations etc, but I've landed on having the tests in the same directory as the package, as seen in the tree structure. For reference, testing_utils.py imports release_all_in_one.utils and that works fine. I am running it with python -m pytest.

company_release/
├── release_all_in_one
│   ├── changelog_utils.py
│   ├── confluence_email.py
│   ├── confluence_utils.py
│   ├── create_confluence_page.py
│   ├── __init__.py
│   ├── jira_utils.py
│   ├── parse_confluence.py
│   ├── release_all_in_one_openshift.py
│   ├── release_all_in_one.py
│   ├── tag_branch.py
│   ├── templates
│   │   ├── admin_package_template
│   │   ├── base_template
│   │   ├── cdn_package_template
│   │   ├── fe_package_template
│   │   ├── oddjob_package_template
│   │   ├── openshift_template
│   │   └── procedure.json
│   ├── testing.py
│   └── utils.py
├── setup.py
├── seutp.cfg
└── tests
    ├── test_changelog.py
    ├── testing_utils.py
    └── test_utils.py

I would love some advice on how these are supposed to imported correctly. I've read over a lot of documentation with no luck.

UI testing : Read out color components

I do Ui tests in visual studio (C#), mainly with the framework teststack.White. However, it is not possible to read colors or similar with any of the frameworks I use. Among other things I tried this with the ui test frameworks "Winium" and "CodedUI".

I have already read out single pixel colors (CopyFromScreen()), at screen resolutions above 100 percent, the bitmaps are taken up however at the wrong "screen place", and thus also at the wrong place in the application -> The color value to be compared is not correct. Among the free ui test frameworks, teststack.white is, in my experience, already the most comprehensive, but it reaches its limits (of course I would like to be taught better).

If anyone has a solution to this problem, I would be happy to be a part of it. I'm looking for a way to read colors and maybe other "hidden" values within the automatic test process without making bitmaps or the like.

Timeout - Async callback was not invoked within the 120000ms timeout specified by jest.setTimeout.Error

detox test -c android.emu.debug is throwing error as below as test cases are not running.

Timeout - Async callback was not invoked within the 120000ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 120000ms timeout specified by jest.setTimeout.

  at mapper (../node_modules/jest-jasmine2/build/queueRunner.js:25:45)


  ReferenceError: device is not defined

  1 | describe('Example', () => {
  2 |   beforeEach(async () => {
> 3 |     await device.reloadReactNative();
    |           ^
  4 |   });
  5 | 
  6 |   // it('should have welcome screen', async () => {

  at device (firstTest.spec.js:3:11)


  at device (firstTest.spec.js:3:11)
  at tryCatch (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:62:40)
  at Generator.invoke [as _invoke] 
  (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:288:22)
  at Generator.prototype.(anonymous function) [as next] 
  (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:114:21)
  at tryCatch (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:62:40)
  at invoke (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:152:20)
  at ../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:187:11
  at callInvokeWithMethodAndArg 
  (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:186:16)
  at AsyncIterator.enqueue 
  (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:209:13)
  at AsyncIterator.prototype.(anonymous function) [as next] 
  (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:114:21)
  at Object.<anonymous>.runtime.async 
  (../node_modules/@babel/runtime/node_modules/regenerator- 
  runtime/runtime.js:233:14)
  at Object._callee (firstTest.spec.js:2:14)


  ReferenceError: element is not defined

   8 |   // });
   9 | 
  10 |   it('should have splash screen', async () => {
     |                                   ^
  11 |     await expect(element(by.id('splash'))).toBeVisible();
  12 |   });
  13 | 

Detox installation:

npm install detox --save-dev

detox init -r jest

which has created e2e folder with three files looks as below:

fristTest.spec.js

describe('Example', () => {
    beforeEach(async () => {
    await device.reloadReactNative();
});

it('should have welcome screen', async () => {
    await expect(element(by.id('welcome'))).toBeVisible();
});

it('should show hello screen after tap', async () => {
    await element(by.id('hello_button')).tap();
    await expect(element(by.text('Hello'))).toBeVisible();
});

it('should show world screen after tap', async () => {
    await element(by.id('world_button')).tap();
    await expect(element(by.text('World!!!'))).toBeVisible();
});
});

config.json

{
    "setupTestFrameworkScriptFile": "./init.js",
    "testEnvironment": "node"
}

init.js

const detox = require('detox');
const config = require('../package.json').detox;
const adapter = require('detox/runners/jest/adapter');

jest.setTimeout(10000);
jasmine.getEnv().addReporter(adapter);

beforeAll(async () => {
    await detox.init(config);
});

beforeEach(async () => {
    await adapter.beforeEach();
});

afterAll(async () => {
    await adapter.afterAll();
    await detox.cleanup();
});

Details about devDependencies under package.json

"devDependencies": {
"@babel/core": "^7.3.4",
"@babel/preset-env": "^7.4.2",
"babel-jest": "^24.5.0",
"detox": "^12.0.0",
"detox-expo-helpers": "^0.6.0",
"jest": "^24.5.0",
"metro-react-native-babel-preset": "^0.53.1",
"mocha-react-native": "^0.6.0",
"react-test-renderer": "16.8.3",
"redux-mock-store": "^1.5.3"
},
"jest": {
"preset": "react-native"
},
"detox": {
"runner-config": "e2e/config.json",
"configurations": {
  "android.emu.debug": {
    "binaryPath": "android/app/build/outputs/apk/debug/app-debug.apk",
    "build": "cd android && gradlew assembleDebug assembleAndroidTest - 
 DtestBuildType=debug && cd ..",
    "type": "android.emulator",
    "name": "Nexus_S_API_27"
  },
  "android.emu.release": {
    "binaryPath": "android/app/build/outputs/apk/release/app-release.apk",
    "build": "cd android && ./gradlew assembleRelease assembleAndroidTest 
 -DtestBuildType=release && cd ..",
    "type": "android.attached",
    "name": "Nexus_5X_API_26"
  }
  },
  "test-runner": "jest"
  }

I tried many threads but nothing worked for me. Finally posting from my side, thanks in advance.

Spec mocha reporter doesn't produce correct output in terminal while webstorm does

I am trying to write mocha tests for rest api calls for my backend. I wrote a basic test and it displays output properly when I see in IDE. But on running npm run test, the command produces random output as mentioned below. Following are my files for reference:

index.spec.ts with rest api tests

process.env.NODE_ENV = 'test';

import 'mocha';
import * as chai from 'chai';
import {server} from "../../bin/www";

const expect = chai.expect;

import chaiHttp = require("chai-http");

chai.use(chaiHttp);

describe("Hello API Request", function () {

    it("should return status 200", async () => {
        const request = chai.request(server);
        const res = await request.get("/");
        expect(res.status).to.eql(200);
    });

    it("should return status 400", async () => {
        const request = chai.request(server);
        const res = await request.get("/");
        expect(res.status).to.eql(400);
    });
});


package.json file

{
  "name": "co-admin-backend",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "ts-node ./bin/www",
    "tslint": "./node_modules/.bin/tslint --project tsconfig.json",
    "build": "npm run tslint && tsc",
    "test": "./node_modules/.bin/mocha --require ts-node/register test/**/*.spec.ts"
  },
  "dependencies": {
    "@types/node": "^10.11.0",
    "archiver": "^3.0.0",
    "body-parser": "~1.18.2",
    "child-process-promise": "^2.2.1",
    "cookie-parser": "~1.4.3",
    "cors": "~2.8.3",
    "csv-parse": "^3.2.0",
    "debug": "~4.1.0",
    "express": "~4.16.0",
    "firebase-admin": "^6.1.0",
    "fs-extra": "^7.0.0",
    "instagram-private-api": "^0.6.8",
    "jsonwebtoken": "~8.4.0",
    "mkdirp": "^0.5.1",
    "mkdirp-promise": "^5.0.1",
    "moment": "^2.22.1",
    "morgan": "^1.9.1",
    "multer": "^1.3.0",
    "p-limit": "^2.1.0",
    "request": "~2.88.0",
    "request-promise": "^4.2.2",
    "rotating-file-stream": "^1.3.9"
  },
  "devDependencies": {
    "@types/chai": "^4.1.7",
    "@types/mocha": "^5.2.6",
    "chai": "^4.2.0",
    "chai-http": "^4.2.1",
    "eslint": "^4.13.1",
    "eslint-plugin-promise": "^4.0.1",
    "mocha": "^6.0.2",
    "nodemon": "^1.18.10",
    "ts-node": "^7.0.1",
    "tslint": "^5.11.0",
    "typescript": "^3.2.1"
  }
}

Test for comparing 2 numbers work fine

index.spec.ts output with normal test

The output for api request is obtained fine here in Webstorm

index.spec.ts output with api request test

The output for api request is not shown properly in terminal

package.json file

I want to fix the terminal output when I run npm run test. Any ideas how this could be fixed?

How to test multiple withLatestFrom store injections in NgRx-Effects?

In our angular webapp we have some NgRx-effects that use different information from different parts of our store. For this we are using the recommended withLatestFrom-approach:

withLatestFrom(
   this.store.pipe(select(...)),
   this.store.pipe(select(...)),
   ...
)

While this approach seems to be working fine in production, it feels horrible for unit testing the effects.

For our unit-tests we are currently using jasmine-marbles, jasmine spy-objects and the ngrx MockStore (NgRx 7+). The hard part is to provide the necessary store state, so that the selectors can work properly.

EXAMPLE-EFFECT, for which we do not have a unit-test:

@Effect()
getStammdatenDetails$: Observable<Action> = this.actions$.pipe(
   ofType(StammdatenItemDetailActionTypes.REQUEST_DETAILS),
   withLatestFrom(
      this.store.pipe(select(fromRoot.getMetadata)),
      this.store.pipe(select(fromRoot.getCustomerId)),
      this.store.pipe(select(fromRoot.getRouterParams))
   ),
   mergeMap(([action, metadata, customerId, params]) => {
      *effect logic*
   })
);

Maybe someone here can provide more insight or a useful link to a piece of documentation we are missing?

I would really appreciate any help in regards if there is a convenient method to unit tests such effects, or how to refactor those effects to be more "testable" (without moving the problem to another piece of code, which we cannot test afterwards).

Jasmine - Check for fit

Following Problem:

I have build pipeline that gets triggered whenever a commit to a specific branch is pushed. This pipeline will run all the unit tests before deploying the application to the productive environment.

Now sometimes members tend to forget to remove the fit statements from their tests wich will make the unit tests pretty easy to pass the pipeline even if the application has errors.

Question:

Is there a way to check if a fit statement is used and return a non-zero exit code if this is the case so I can make sure the pipeline fails

Testing JPAQueries with TestEntityManager

I have a service, which fetches complicated JPAQueries. I have to write h2 database tests for this service. The autowired service in this "fetching" service builds the JPAQueries. So I have to mock this autowired service and I have to return the builtQuery for the fetching service. I made a tutorial from Baeldung for this, and this says I have to use the TestEntityManager. Now I want to build the JPAQuery for returning of the QueryBuilderService which is mocked. When I made

new JPAQuery(entityManager)

It wants the EntityManager as param and not the TestEntityManager.

Do anybody have a good solution for this? Exists something like "TestJPAQuery" or something? Please help :)

How to know if an internal tester has installed the app or not

I have set up an internal testing channel and have added a few testers for my app. But could not find a way to check if a particular tester from the list has installed the app or not.

I know this can be found out in Appstore. We get to know who has installed the app. I tried the firebase analytics dashboard and play console dashboard for the app, app statistics etc, but no luck. Is there a way to find this in Playstore?

Laravel Testing/phpunit, Too few arguments passed when using dependency injection

I'm trying to create a simple test with Laravel. My test code is as below;

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Http\Controllers\Abc\AbcController;

class AbcTest extends TestCase
{

 /**
 * A basic test example.
 *
 * @return void
 */

private $abcController;

public function __construct (AbcController $abcController) {
    $this->abcController = $abcController;
}

public function testExample()
{
    $this->assertTrue(true);
}

However, when i run the test, i'm hitting this error,

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Tests\Feature\abc::__construct(), 0 passed in /var/www/nex/backend/vendor/phpunit/phpunit/src/Framework/TestSuite.php on line 151 and exactly 1 expected in /var/www/nex/backend/tests/Feature/abc.php:28

I've been using this method of performing dependency injections for the rest of my project. I'm not sure why its not working on this particular code.

All help is appreciated.

Thanks!

mercredi 27 mars 2019

How to run a os cli command in jest test case and check for file creation

I am looking for something to run a os command like node index.js and i want to check for the file created by it. Its a cli project so I want it to run as a cli command. It should be some like

test('running command node index should give me a new folder', () => {
   // my cli command here
  expect file assertion
});

It is much similar to yeoman-assert and yeoman-helpers

Thanks

PDO Extention on laravel unit testing

I've been struggling with setting up unit test with my laravel application, I'm facing error... it says that PDO extention is not installed and giving me error that pdo exeption driver not found but it's installed!!!. when i serve my application everything is ok!!!

pdo is also installed

  28 => "json"
  29 => "exif"
  30 => "mysqli"
  31 => "pdo_mysql"
  32 => "pdo_sqlite"
  33 => "Phar"
  34 => "posix"
  35 => "readline"
  36 => "shmop"

here is my test code

<?php

namespace Tests\Unit;

use App\Models\User\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        factory(User::class)->create();
        $this->assertTrue(true);
    }
}



trace of error

 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Connection.php:624
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Connection.php:459
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Connection.php:411
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/Processor.php:32
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2653
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:1347
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:835
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:800
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:663
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:206
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Support/Collection.php:419
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:207
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:181
 /home/soheil/Documents/Projects/PHP/EcollegeMe/tests/Unit/ExampleTest.php:18

 Caused by
 PDOException: could not find driver



What are different between Regression testing and test re running in Quality assurance?

I'm a beginner of software testing and I'm referring about testing type. Then I have met this question.

Very green VBA user, everything below 2nd line works, but how do I make above it work?

I have made a test in Excel for my cousin; right now if you get the answer correct then you have to press a button for the next question, but I would like the macro to show "correct" for 2 seconds then move on to the next question without having to press a button. Please help

I've tried below, it used to be regular button click macro, but i've tried to change it and it won't run

Sub answer_correct()

If K11.Value == "Correct!" Then

Range("A1") = WorksheetFunction.RandBetween(1, 65)

Range("I11").Cells.ClearContents

ActiveSheet.Range("I11").Select

Range("F18").Value = Range("F18").Value + 1

End If

End Sub

I get syntax error, I expect the counter to go up by 1 and the question to reset

Testing a exported Constant Object

im having some problems when i am testing my constants.ts file: the file contains:

constants.ts:

export const Constants = Object.freeze({
"key":"value",
"key2":"value",
"key3":"value",
"key4":"value",

})

Sonar tells me that I need to coverage the line: export const Constants = Object.freeze({.

How can i do the spec file to test it?

Im new with testing in angular, and I'm getting mad with this world xD

Junit5 and Instrumentation Tests running when running unit tests

I upgraded my tests to junit5 now when I run my unit tests it also runs my instrumentation test which of course causes errors as they're not running in a simulator. How do I stop it from running them? I was able to solve some of the errors using @RunWith(AndroidJUnit4::class) but I still have one error and it’s driving me crazy :stuck_out_tongue_winking_eye:

this is the error, however, I do not understand why my instrumentation tests are now running when I click on Run???

java.lang.NoClassDefFoundError: androidx/test/espresso/matcher/ViewMatchers

    at com.magtec.magtecmcc.MainActivityTest.testLaunch(MainActivityTest.kt:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:531)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:256)
    at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: androidx.test.espresso.matcher.ViewMatchers
    at org.robolectric.internal.bytecode.SandboxClassLoader.getByteCode(SandboxClassLoader.java:164)
    at org.robolectric.internal.bytecode.SandboxClassLoader.maybeInstrumentClass(SandboxClassLoader.java:119)
    at org.robolectric.internal.bytecode.SandboxClassLoader.lambda$findClass$0(SandboxClassLoader.java:112)
    at org.robolectric.util.PerfStatsCollector.measure(PerfStatsCollector.java:53)
    at org.robolectric.internal.bytecode.SandboxClassLoader.findClass(SandboxClassLoader.java:111)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 19 more

Multiple ways of performing an action with the page object pattern

When implementing the page object pattern, the recommendation that I've seen is that actions should be high-level, instead of individual UI actions:

For example:

page.search(query)

Rather than:

page.enterSearchBarText(query)
page.clickSearchButton()

However, the search should also execute when the user hits Enter instead of clicking the search button.

So search could also be:

page.enterSearchBarText(query)
page.pressEnter()

If I want to cover both in my tests, what is a conventional way of implementing this? I thought perhaps

search(query, method)

where method could be one of enum { SearchButton, Enter }

How to create a 500 error on an rest API for error testing purpose?

I am writing some test code for my rest api using nodejs and chai.

I would like to create a 500 error on purpose to be sure my API react well, but I have no idea on how to do that.

Any help or tips about best practices would be really appreciated. Thanks in advance

How do i test if a variable has a react component as value?

I have a variable which gets dynamically assigned a React component based on a condition is true or false. if(isValid) {icon = } else {icon =

how do i test for expected value of icon is one component or other?

How to mock/test event listeners with mocha/jest?

class Router {
    constructor() {
        window.onhashchange = this.hashChange;
    }

    hashChange() {
        console.log('Hash Changed');
        return true;
    }
}

export default Router;

I am trying to find a way to test the above piece of code in node.js. But there is no window object in node. How to mock objects and test event listeners using mocha/jest? The goal is to test that hashChange() is invoked when URL hash is changed

Mobile testing concurrent with Web testing in UFT - Tools option?

We have designed few functional automation scripts using UFT for our Web and AS400 applications. Now we are planning to add mobile testing to our test suite for E2E testing. Below is a sample test case.

Test steps:

Step 1: Login to the web application/AS400 and do some changes(This triggers a notification in mobile app)

Step 2: Open the mobile app and validate if the notification is popping up in the app. If yes click on a link in the app.

Step 3: Check on the Web browser/AS400 if the notification is accepted from the mobile device

Guidance needed for below items considering above steps:

  1. Can UFT be leveraged for Mobile automation without additional license. Currently we have UFT 14.

  2. Do we need Mobile center to do mobile automation

  3. Can we integrate with any opensource tools like Appium directly without Mobile center. If yes will the test work for above concurrent steps.

  4. How can i find the other Mobile testing tools which go along with UFT

How to create Unit / NUnit / XUnit Tests for a Visual Studio Extension projects (VSIX) using Visual Studio 2017?

On VS 2015 you can test your VSIX projects using XUnit / NUnit / Basic Unit Tests from Visual Studio. Unfortunately, this way is not possible anymore in VS 2017 and VS 2019. Some attributes are now deprecated and I cannot find a replacement for them.

At this moment I am trying to find a way to test my VS Extensions using Visual Studio 2017. Any help is appreciated.

Thanks!

How just to start Kestrel server from xUnut test

I have set of xUnit tests that have to make requests to running Kestrel server. There is a code that runs the only once before tests in the beginning and has to run Kestrel server on the specific port.

I know about Microsoft.AspNetCore.TestHost package. It has TestServer class that lets to create client to make requests to the server. But my unit tests are testing classes that encapsulate HttpClients inside already.

So, I need just to run server on specific port in the beginning. How can I to do that?

Vertx.io core vs reactivex verticle usage in jUnit

In my project mostly all imports relay on io.vertx.reactivex.core.Vertx package import, effectively makes whole project use reactivex (not core/vanilla) version of Vertx and it's verticles. I started to unit test a bit our application and to do so and to make it play nicely with JUint, according to this documentation following setup is needed to use JUnit and to run test cases in correct thread and verticle context:

@RunWith(VertxUnitRunner.class) /* Set the runner */
public class DaoTest {

    @Rule /* Define rule to get vertx instance in test */
    public RunTestOnContext rule = new RunTestOnContext();

   @Test
    public void exampleTest(TestContext context) {
       TestClass t = new TestClass(rule.vertx());
   }
}

the definition of TestClass is following:

import io.vertx.reactivex.core.Vertx; /* Mind here */
public class TestClass {

    public TestClass(Vertx vertx) {
        /* Something */
    }

I'm unable to provide correct instance of Vertx because only one definition of RunTestOnContext exist in package io.vertx.ext.unit.junit and produces io.vertx.core.Vertx instance, which is incompatible with io.vertx.reactivex.core.Vertx that TestClass is using. Some other test utilities, like TestContext have their equivalents in reactivex packages io.vertx.reactivex.ext.unit.TestContext, but this seems not be a case for RunTestOnContext.

The question would be how to obtain correctly io.vertx.reactivex.core.Vertx instance in test context to still ensure thread and context consistency?

Nested testRunners: Can I runClasses separating tests?

background

I am building a small frame using Cucumber and Junit-quickcheck. Guidelines require writing the scenarios in cucumber and I want to add the possibility of running property based tests. With quicktheories this works fine, but there are some bugs there and it's maintained by a single person so I'd like to switch to junit-quickcheck.

the question

The code works fine but the two tests are now run as one, and in the cucumber report it's not possible to identify them. So what I'd like is to find a way to write the pbt-tests in the PBT class (not as a class for each test!) and then execute them with cucumber as separate tests.

I suppose there should be a way using the TestClass maybe, but I haven't been able to get that working.

Here is my code that runs, but only as described:

public class Steps implements En {
  public Scenario scenario;
}


public Steps() {

  Given("^I exeute a pbt$", () -> {
    System.out.println("Lets run the pbt");
    Result res = JUnitCore.runClasses(PBT.class);
    assertThat(res.getFailures().toString(), res.wasSuccessful(), equalTo(true));
  });

  }
}

and:

@RunWith(JUnitQuickcheck.class)
public class PBT {
  @Property public void concatenationLength(String s1, String s2) {
    assertEquals("nahh", s1.length() + s2.length(), (s1 + s2).length());
  }

  @Property public void reverseTwice(String str){
    assertThat(new StringBuilder(str).reverse().reverse().toString(), equalTo(str));
  }
}

Gives this result:

Running steps.TestRunner
Feature: PBT
Lets run the pbt

  @PBT
  Scenario: First example # PBT.feature:3
    Given I exeute a pbt  # Steps.java:40

1 Scenarios (1 passed)
1 Steps (1 passed)
0m0.597s

how to set image (from drawable for example) to imageView while espresso test?

I am using espresso test recording for capture image from camera and set the image into the imageView, I couldn't do that because I when press on the camera capture button its not recording for obvious reason, so the way to do that is to mock the capture image process I found some code to do that but no luck.

I tried this code from here How to set image in imageview while testing with espresso?

public static void simulatePictureFromCameraRoll(Uri pictureUri) throws  Exception {
    Exception returnException = null;
    Intent resultData = new Intent();

    resultData.setData(pictureUri);

    Intents.init();
    try {
        Matcher<Intent> expectedIntent = hasAction(Intent.ACTION_GET_CONTENT);
        intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData));
        onView(withId(R.id.newUpdatedIDCardImg)).perform(click());
        intended(expectedIntent);
    }
    catch (Exception e) {
        returnException = e;
    }
    finally {
        Intents.release();
    }

    if (returnException != null) {
        throw returnException;
    }
}

and here how I use that method, I used some drawable image :

intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(
            new Instrumentation.ActivityResult(Activity.RESULT_OK, null));


    //Uri uri = Uri.parse("R.drawable.bg_shape");
    Uri myURI = Uri.parse("android.resource://com.example.project/" + R.drawable.bg_shape);

    try {
        simulatePictureFromCameraRoll(myURI);
    } catch (Exception e) {
        e.printStackTrace();
    }

what I want is to simply set an image in the imageview with espresso, please help me and thanks in advance.

How to click drop down (which is not created by select ) using selenium webdriver (eclipse)?

I tried to select a value of the drop down for "Payment Method" at the following page.

Login to https://my.orderhive.com/

Redirect to https://my.orderhive.com/orders >> Click "New Order" button

On this page, there is a drop down for "Payment Method". I want to select "Cheque" value for that drop down.

I tried to select using link text, XPath, select & Actions. But, none of them are working.

How to keep tests from failing when running tests in parallel and switching iframes?

I'm currently mantaining a solution of tests using selenium and specflow, and I was running everything in parallel smoothly, sharing a sigle webdriver between browser(chrome) windows.

But now i had to add a couple of scenarios that involve switching between frames, and the tests started to break randomly when run in parallel due to elements or iframes not being found.

Anyone has had this problem and knows a good way to solve this?

iOS| how to do automated and repeated launching of an app?

I want a simplest was to do this:

  1. Simulate a tap where my app icon is on screen (this is a fixed location so the x-y coordinates can be hard coded). Basically, I want to launch a particular app installed on my iPad.
  2. Wait for 10 seconds
  3. Simulate home button press
  4. Wait for 2 seconds.

My app connects and communicates with a server when it launches, and I want to do some reliability testing with the actual app running on iPad.

What is the simplest was to doing this?

Thanks you.

How to verify if a node that might either contain a null or a string in the response body using Postman?

I need to verify whether a particular node in the response body of an API is null or a string. How is it done using ChaiJS in postman tests?

Sample API response body:

[
 {
   "exercise_num": "1",
   "expire_date": "2019-03-11T16:31:17.935Z",
   "created_at": "2019-03-15T11:44:35.698Z"
 },
 {
    "exercise_num": "2",
    "expire_date": null,
    "created_at": "2019-03-15T11:44:38.363Z"
 }
]

I would like to verify that the expire_date node in the above sample API response body will either only contain null or a string data type and it won't return any other data type such as int, etc.

I have tried the following:

var jsonData = JSON.parse(responseBody);
pm.test('All expire_date contains either string or null', () => {
for (i = 0; i < jsonData.length; i++) {
if(jsonData[i].expire_date === null){
tests["expire_date is null"] = true;
}
else{
    pm.expect(jsonData[i].expire_date).to.be.a('string');
}
}
});

The test passes.

I'm expecting if something like this can be done:

pm.test('All expire_date contains string', () => {
for (i = 0; i < jsonData.length; i++) {
    pm.expect(jsonData[i].expire_date).to.be.a('string' || null);
}
});

Is there a way to find all tests associated with a specific class on any level?

I'm using Intellij IDEA to program a project in java. I'm trying to test a class which I've changed and I want to get a list of all the tests that use it on any level.

Is there a way to do it in Intellij? Any external tool apart from IDEA can be good too.

I know how to get the direct unit tests(That's possible using CTRL+SHIFT+t) but I also want other tests as well that test the class on more complex level).

I want to find tests that might use the class C as follows:

Test A runs class B which uses class C.

So I want to find Test A and other like it.

mardi 26 mars 2019

Dynamic browser resolution for Protractor testing

my question concerns end to end testing scenario involving a responsive web app. I have written my test scenario for the pages to test with different test cases depending on the screen resolution. I am using array variables to store the different selectors linked to the same element, for example:

  it('should display the log in page', function () {
    gVar.signInButton = element(by.css(gVar.signInButtonSelector[gVar.SelectedMode]));
    gVar.signInButton.click().then(function(){
      expect(element(by.css(gVar.titleLoginPageSelector[gVar.SelectedMode])).getText()).toEqual(gVar.titleLoginPage[i]);
    });

Here I am trying to select the login page title to test it. Depending on the resolution, only the selector is different, and I stored them in arrays...

In my conf.js I have a parameter variable that I use in the command line to set the configuration I want to use:

    exports.config = {
    //...

      params:{
            resolutionConfig:'default'
            },  

    //...
    }       

the run command can go:

protractor conf.js --params.resolutionConfig=Classic or

protractor conf.js --params.resolutionConfig=Mobile or

protractor conf.js --params.resolutionConfig=Tablet ...

(Then I have a matching table to associate this parameter to the above integer value: gVar.SelectedMode)

What I would like to do now, is to set different resolutions values for my browser, a different one for each value of resolutionConfig parameter I am testing. So far, I know how to set that resolution with hardcoded values:

    exports.config = {
    //...

    capabilities: {
        browserName: 'chrome',
        chromeOptions: {
            args: ['--window-size=100,100'] // THIS!
        }

    //...
    }       

I have heard of "multicapabilities" to run parallel tests, but it is not exactly what I want… is it possible to have the resolution parameters in variable and add a logic to it? Something like:

    if(resolutionConfig) is "mobile" then: ['--window-size=xx,xx']; 
    if(resolutionConfig) is "tablet" then: ['--window-size=yy,yy'];

Running same tests on multiple functions using Jasmine

I am trying to test a suite of testing functions with a file structure like so:

- sorting
   - algorithm 
      - bubble.js
      - insertion.js 
   - test 
      - test.spec.js 

each sort.js file looks something like this:

var mergeSort = function(A) {
// ... implementation
}

module.exports = { mergeSort };

what is the best way for me to include all of these inside of test.spec.js, and run the same tests on all of them? currently I am basically just doing tests like this (for linked-list)

describe('Stringify', function () {

    let list1 = new LinkedList(); 

    it('adds, removes, stringifies', function () {
      expect(list1.stringify()).toEqual('');
      list1.insertToBeginning(1); 
      expect(list1.stringify()).toEqual('1');
      list1.insertToBeginning(1); 
      list1.insertToBeginning(2); 
      list1.insertToBeginning(3); 
      expect(list1.stringify()).toEqual('1');
    });

  });

but this will be too much for testing a suite of potentially many sorting algorithms. I would like to specify a bunch of tests, and run them all on the list of functions that I require.

How to test my flood it solver algorithm by universal standard?

We are developing a flood it game solver by Greedy and A* search for an Ai project, how can we test it our algorithm is optimal and good or not ? we used a code that sets number of moves by taking the minimum of multiple runs, so far our solver works greatly with high wining rate,

but how can we test the algorithm for real ? we didn't use any standards but devolved a simple algorithm using only a set of arrays

ansible: get list of subelements and assert for duplicates

Given a dictionary, assert for duplicates in the same list.

vars.yml file :

---
customer_domains:
  - name: myBank.org
  - name: myBakery.net
  - name: mySchool.edu
    smtp_username: smtp-school
    sender_domains:
      - sender1.tld
  - name: myRestaurant.net
  - name: myHouse.org
    smtp_relay_host: smtp-house.org
    smtp_relay_port: 25
    sender_domains:
      - test1.com
      - test1.com
      - test2.net
      - test3.house.net

What we really want is to make sure we don't have duplicate sender_domains for every name. Same sender_domains but in different names are allowed.

Doing a bit o research I was able to create the following task, which shows the value of sender_domains in every execution. However, what we really want is a list of all sender_domains from every name so we can assert for duplicates afterwards.

- name: DEBUG VAR=ITEM.1
  debug: var=item.1
  with_subelements:
    - ""
    - sender_domains

Thoughts?

This works to print subelements of customer_domains var:

- name: print customer_domains SUBELEMENTS
  debug:
    msg: ""
  with_subelements:
    - ""
    - sender_domains

How to make textbox appear when turning off Android Smartphone

I'm writing a simple app for Android. It's very simple yet, it just take as input a username and a password.

I need to store those user and pwd firstly, then I need to make a textbox asking for those user and password appear when I try to turn off the smartphone. Could you please help me on how to do it?

How to properly test a service method that uses other services

I'm stuck on how to properly test a method on a Symfony service which only purpose is to call other methods on other services.

Trying to unit test the method by mocking every depencency, and relative methods, it uses, just makes the test useless in my opinion, since what i'm testing, in a way, is just that the other services are called correctly. Also, as i read on various sources, i shouldn't mock what i don't own, and basically all such methods use at least one (EntityManager, EncoderFactory, ecc...)

Trying to function test it with booting the kernel, grabbing the service and calling the method was a nightmare, and i got stuck on asserting that emails was sent, since i need a client and a response to grab all the emails that've been sent from the profiler.

This is an example of such methods that i have to test:

public function postRequestCreatedActions(PrivacyRequest $request, $sendNotifications = true)
{
    $this->customLogger->logRequest($request);
    if ($sendNotifications) {
        $this->customMailer->sendRequestCreated($request);
    }
    $this->em->flush();
}

So, my question is: if there's a way to properly test methods like this (unit or functional), how should i test it? If a method like this is untestable, and needs to be changed, or removed entirely, how do you advice to refactor it without clogging the controller that calls it (each one is called by a controller)? Or is moving all this logic to the controller the only way?

Thanks

Travis CI: Split Builds from PHPUnit and Laravel Dusk

I would like to set up a testing scenario where, I can separate the test-builds for phpunit and laravel dusk. The reason why is, tahat this I would like to run different .env & phpunit.xml files for each test-approach.

  1. Set the environment for PHPUnit
  2. Test PHPUnit
  3. Clean the Travis Build
  4. Set the environment for Laravel Dusk
  5. Test Laravel Dusk

I've went through the Travis documentation about jobs and the matrix but I cant find a proper approach which I can follow.

my .travis.yml

    sudo: true

    dist: trusty

    language: php

    php:
      - 7.3

    addons:
      chrome: stable
      apt:
        sources:
          - mysql-5.7-trusty
        packages:
          - mysql-server
          - mysql-client

    services:
      - mysql

    install:
      - composer self-update
      - travis_retry composer install --no-interaction --prefer-dist --no-suggest

    before_script:
      - rm composer.lock
      - echo -e "[server]\nmax_allowed_packet=64M" | sudo tee -a /etc/mysql/conf.d/drupal.cnf
      - sudo service mysql restart
      - mysql -e 'CREATE DATABASE testing;'
      - mysql -e 'CREATE DATABASE business_external;'
      - mysql business_external < /home/travis/build/StanBarrows/business/database/data/business_external
      - google-chrome-stable --headless --disable-gpu --remote-debugging-port=9222 http://localhost &
      - cp .env.travis .env
      - cp phpunit.travis.xml phpunit.xml
      - php artisan key:generate
      - php artisan storage:link
      - php artisan serve &

    script:
      - vendor/bin/phpunit
      - php artisan dusk

    notifications:
      email: false

Error when running e2e tests in Visual Studio 2017 with MVC dotNet Core 2.2 and Angular 7

Trying to set up some e2e testing in VS2017 for an dotnet core 2.2 MVC app that fronts an Angular 7 SPA.

When I run the default tests from Visual Studio, the tests come back as "Ignored: Task skipped on timeout". I also get a Jasmine page in a browser with lots of errors.

tsconfig.e2e.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {

    "outDir": "../out-tsc/app",
    "module": "commonjs",
    "target": "es5",
    "types": [
      "jasmine",
      "jasminewd2",
      "node"
    ]
  }
}

protractor.conf.js

// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require('jasmine-spec-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome'
  },
  directConnect: true,
  baseUrl: 'http://localhost:53092/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  onPrepare() {
    require('ts-node').register({
      project: require('path').join(__dirname, './tsconfig.e2e.json')
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};

app.e2e-spec.ts

import { AppPage } from './app.po';
import { browser, logging, by } from 'protractor';

describe('workspace-project App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });


  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getTitleText()).toEqual('Welcome to a7app!');
  });

  afterEach(async () => {
    // Assert that there are no errors emitted from the browser
    const logs = await browser.manage().logs().get(logging.Type.BROWSER);
    expect(logs).not.toContain(jasmine.objectContaining({
      level: logging.Level.SEVERE,
    } as logging.Entry));
  });
});

app.po.ts

import { browser, by, element } from 'protractor';

export class AppPage {
  navigateTo() {
    return browser.get(browser.baseUrl) as Promise<any>;
  }

  getTitleText() {
    return element(by.css('app-root h1')).getText() as Promise<string>;
  }
}

lines of jasmine output

0 specs, 0 failures, randomized with seed 84783
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/runner.js line 1
Error during loading: Uncaught TypeError: logger_1.Logger is not a constructor in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/index.js line 28
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/driverProvider.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/useExistingWebDriver.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'logger_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/kobiton.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'logger_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/testObject.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'logger_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/sauce.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/mock.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'logger_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/local.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'logger_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/hosted.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/direct.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'logger_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/browserStack.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/driverProviders/attachSession.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'chrome' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/ptor.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/locators.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/expectedConditions.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/element.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/browser.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'selenium_webdriver_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/debugger.js line 1
Error during loading: Uncaught ReferenceError: goog is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/webdriver-js-extender/index.js line 8
Error during loading: Uncaught SyntaxError: Identifier 'blockingproxy_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/blocking-proxy/built/lib/client.js line 1
Error during loading: Uncaught TypeError: Cannot read property 'FindElement' of undefined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/blocking-proxy/built/lib/webdriver_logger.js line 20
Error during loading: Uncaught SyntaxError: Identifier 'webdriver_commands_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/blocking-proxy/built/lib/highlight_delay_barrier.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'http' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/blocking-proxy/built/lib/webdriver_proxy.js line 1
Error during loading: Uncaught TypeError: Class extends value undefined is not a constructor or null in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/blocking-proxy/built/lib/webdriver_commands.js line 112
Error during loading: Uncaught SyntaxError: Identifier 'http' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/blocking-proxy/built/lib/simple_webdriver_client.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'chrome' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/index.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'http' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/safari.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/remote/index.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/phantomjs.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/opera.js line 1
Error during loading: Uncaught TypeError: Cannot read property 'addImplementation' of undefined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/webdriver.js line 2442
Error during loading: Uncaught SyntaxError: Identifier 'by' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/until.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'Capabilities' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/session.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'error' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/promise.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/logging.js line 664
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/input.js line 167
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/events.js line 207
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/error.js line 563
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/command.js line 241
Error during loading: Uncaught SyntaxError: Identifier 'Symbols' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/capabilities.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/by.js line 282
Error during loading: Uncaught SyntaxError: Identifier 'command' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/actions.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/ie.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'http' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/http/index.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'error' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/http.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/atoms/is-displayed.js line 2
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/atoms/get-attribute.js line 2
Error during loading: Uncaught SyntaxError: Identifier 'http' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/firefox/index.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'Executor' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/http/util.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/firefox/profile.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/firefox/extension.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'path' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/io/zip.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/firefox/binary.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'Command' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/io/exec.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/devmode.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/edge.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/chrome.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/net/portprober.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/lib/symbols.js line 26
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/io/index.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/selenium-webdriver/node_modules/tmp/lib/tmp.js line 1
Error during loading: Uncaught ReferenceError: process is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/os-tmpdir/index.js line 2
Error during loading: Uncaught SyntaxError: Identifier 'path' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/rimraf/rimraf.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/glob/glob.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/once/once.js line 2
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/inflight/inflight.js line 5
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/wrappy/wrappy.js line 6
Error during loading: Uncaught SyntaxError: Identifier 'path' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/glob/common.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/glob/sync.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/path-is-absolute/index.js line 18
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/inherits/inherits.js line 6
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/inherits/inherits_browser.js line 3
Error during loading: Uncaught SyntaxError: Identifier 'path' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/minimatch/minimatch.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/brace-expansion/index.js line 4
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/balanced-match/index.js line 2
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/concat-map/index.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/fs.realpath/index.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'fs' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/fs.realpath/old.js line 1
Error during loading: Uncaught SyntaxError: Identifier 'logger_1' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/protractor/built/plugins.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/url/util.js line 3
Error during loading: Uncaught SyntaxError: Identifier 'EventEmitter' has already been declared in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/events/events.js line 1
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/querystring/encode.js line 40
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:65086/referenceFile?path=~/ITSAppv303/a7app/node_modules/querystring/decode.js line 31

I'd expect the tests to at least try to run.