jeudi 1 août 2019

How to get the count of unit tests present in the project

I have written some unit tests for my android project. I want to know if there exists a way I can get the count of the total number of unit test executed when I run gradlew test

In the case of UI tests, the count is known to us at the time of test running.

V/InstrumentationResultParser: INSTRUMENTATION_STATUS: numtests=26

I wonder if there exist some way to get so in Unit tests.

Using fixtures with pytest: How to share fixtures and use their parameters in different functions

I am struggling with setting up my fixtures correctly in pytest. I always get a missing 1 required positional argument: error. This is what I am trying:

@pytest.mark.django_db
class TestCreate:

    @pytest.fixture(scope='class')
    def user(self):
        username = 'testuser'
        password = 'mypassword'

        user_data = {
            'username': username,
            'password': password,
        }

        return user_data

    def setup(self, user):
        """Setup for tests to create user and project

        """
        user_d = user
        print(user_d)
        username = user_d['username']


Basically I only want to access the dictionary in from my fixture. But I get E TypeError: setup() missing 1 required positional argument: 'user'

I seems Pytest doesn't have access to my fixtures?

Help is very much appreciated! Thanks in advance

TypeError: wrapper.exists is not a function && TypeError: wrapper.find is not a function

I am writing test cases for one of my component which is having router.and i am getting error wrapper.find is not a function. Basic requirement is need to check the existence of tag in my render,also check the aria-label attribute of tag

const Component = () => const WrappedComponent = withRouter(Component)

  describe('Error Boundary...', () => {
    it('should render children when no error is encountered', () => {
      const wrapper = ReactTestRenderer.create(
        <Router><WrappedComponent /></Router>
      );
      expect(wrapper.toJSON().type).toEqual('div');
      expect(wrapper.toJSON()find('a').attr('aria-label')).toEqual('Hello World');
    });
  });

Test uses internal ContextConfiguration of other test

I created a new test in my Project. For this one I used @ContextConfiguration with an internal Configuration class in the same class as the Test. But now my other tests are failing because they are using the configuration of the new test. How is this possible, I thought it is not possible to use a configuration inside of a test class from outside.

When I remove the internal configuration from the new test every other test works finde again.

@DataJpaTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ContextConfiguration(classes = EventServiceTest.Config.class)
class EventServiceTest {
    @Configuration
    @Import({WorkingTimeConfig.class,
             PartnerConfig.class,
             ProjectConfig.class,
             UserConfig.class,
             AccountGroupConfig.class,
             LanguageConfig.class,
             CountryConfig.class,
             EventConfig.class,
             LanguageConfig.class})
    static class Config {
        @SuppressWarnings("unused")
        @MockBean(reset = MockReset.BEFORE)
        private UserAttendanceBoard userAttendanceBoard;

        @Bean
        public PasswordEncoder passwordEncoder() {
            return PasswordEncoderFactories.createDelegatingPasswordEncoder();
        }

        @Bean
        public ImpersonateProperties impersonateProperties() {
            return new ImpersonateProperties();
        }
    }
...
}

Now this Test is not working:

@Import(MailSenderAutoConfiguration.class)
@DataJpaTest
@Transactional
public class ServiceTimeEntryServiceTest {

    private ServiceTimeService serviceTimeService;
    private ServiceTimeEntryRepository repository;

    @Autowired
    public ServiceTimeEntryServiceTest(ServiceTimeService serviceTimeService, ServiceTimeEntryRepository repository) {
        this.serviceTimeService = serviceTimeService;
        this.repository = repository;
    }

    @Test
    void getAllByAccountId() {...}

This error is thrown if I try to start my old tests:

org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'passwordEncoder' defined in class path resource [de/hlservices/timetracking/api/business/event/EventServiceTest$Config.class]: Cannot register bean definition

Thanks for your help :)

Jest encountered an unexpected token because trying to import a file which Jest cannot parse

PS E:\react\Code\UI> yarn test yarn run v1.17.3 $ jest FAIL src/App.test.js ● Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

E:\react\Code\UI\src\mainpage.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){body{font-size:12px;font-family:arial,sans-serif;background-size:200% 100%!important;height:100vh}
                                                                                             ^

SyntaxError: Unexpected token {

  1 | import React, { Component } from "react";
> 2 | import "../mainpage.css";
    | ^
  3 | import { connect } from "react-redux";
  4 | import propTypes from "prop-types";
  5 | import { fetchPost } from "../redux/action/postaction";

  at ScriptTransformer._transformAndBuildScript (E:\react../../../../Code/UI/node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
  at ScriptTransformer.transform (E:\react../../../../Code/UI/node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
  at Object.<anonymous> (E:\react../../../../Code/UI/src/page/Header.js:2:1)

Test Suites: 1 failed, 1 total Tests: 0 total Snapshots: 0 total Time: 3.592s Ran all test suites. error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Testing @ConfigurationProperties with Mockito

I have configuration class:

@ConfigurationProperties(prefix = "myConfig")
public class MyConfig {
    protected String config;
}

My service uses this config class and I'm trying to test it with Mockito:

@RunWith(MockitoJUnitRunner.class)
public class myTest {

    @InjectMocks
    private MyService myService;

    @Mock
    private MyConfig myConfig;

    @Test
    public void myTest1() {
        myService.getInfo("a");
    }
}

myTest fails since the config class is mocked, thus has null values. What is the right way to test configuration class with Mockito?

Does testcafe support testing of rest api

Tests hang in the testcafe browser when you try to test a rest api url directly.

I am trying to run a test against my rest API endpoint using request hooks, but when I run the test from the command line, the browser opens the API endpoint and loads it and hangs. The test doesn't pass or fail and hangs. The rest API endpoint just returns a JSON response.


const logger = RequestLogger('https://example.com/search/suggestions?search=testkeyword');

fixture `test`
    .page('https://example.com/search/suggestions?search=testkeyword');

test
    .requestHooks(logger)
    ('test', async t => {

        // Ensure that the response has been received and that its status code is 200.
        await t.expect(logger.contains(record => record.response.statusCode === 200)).ok();

        const logRecord = logger.requests[0];

        console.log(logRecord.userAgent);           
        console.log(logRecord.request.url);         
        console.log(logRecord.request.method);      
        console.log(logRecord.response.statusCode); 
    });

I expect the test to pass checking for 200 status code, but the test hangs without showing pass/fail. Does testcafe support testing of rest API endpoints? I have checked this issue - https://github.com/DevExpress/testcafe/issues/1471 where it says testcafe doesn't support non-html pages. Please confirm.