Saturday, July 13, 2024

Java Unit Test MCQ

 Question 1


Which framework is most commonly used for unit testing in Java?


JUnit  

TestNG  

Mockito  

Selenium

Answer:  


JUnit



Question 2

In JUnit 5, which annotation is used to indicate a test method?


@TestCase  

@RunWith  

@Test  

@Before

Answer:  


@Test



Question 3

Which JUnit annotation is used to execute some code before each test method?


@BeforeAll  

@After  

@BeforeEach  

@BeforeTest

Answer:  


@BeforeEach



Question 4

Which method in JUnit is used to check if two objects are equal?


assertSame  

assertTrue  

assertEquals  

assertNotNull

Answer:  


assertEquals



Question 5

Which of the following is a mocking framework often used in Java unit tests?


TestNG  

Mockito  

JUnit  

Cucumber

Answer:  


Mockito



Question 6

In Mockito, which method is used to create a mock object?


mock()  

createMock()  

mockObject()  

newMock()

Answer:  


mock()



Question 7

What does the @Mock annotation do in Mockito?


It creates a real object  

It creates a mock object  

It verifies a method call  

It initializes a mock object

Answer:  


It creates a mock object



Question 8

Which JUnit annotation is used to run a piece of code after all tests in the test class have been run?


@AfterEach  

@AfterAll  

@AfterTest  

@After

Answer:  


@AfterAll



Question 9

In TestNG, which annotation is equivalent to JUnit's @BeforeEach?


@BeforeTest  

@BeforeMethod  

@BeforeClass  

@BeforeSuite

Answer:  


@BeforeMethod



Question 10

Which Mockito method is used to verify that a method was called with specific arguments?


verify()  

check()  

assert()  

confirm()

Answer:  


verify()



Question 11

In JUnit 5, which annotation is used to disable a test method?


@Ignore  

@Disabled  

@Skip  

@Deactivate

Answer:  


@Disabled



Question 12

Which of the following is not a lifecycle method in JUnit 5?


@BeforeEach  

@AfterEach  

@BeforeClass  

@BeforeAll

Answer:  


@BeforeClass



Question 13

Which of the following assertions is used to check if a condition is false in JUnit?


assertTrue()  

assertFalse()  

assertNull()  

assertNotNull()

Answer:  


assertFalse()



Question 14

What is the primary purpose of unit testing?


To test the entire application as a whole  

To test individual units or components in isolation  

To test the user interface  

To test the performance of the application

Answer:  


To test individual units or components in isolation



Question 15

In Mockito, which method is used to return a specific value when a method is called?


when().thenReturn()  

doReturn().when()  

mock().thenReturn()  

verify().thenReturn()

Answer:  


when().thenReturn()



Question 16

Which JUnit annotation is used to provide a timeout for a test method?


@Timeout  

@Test(timeout = 1000)  

@TimeLimit  

@Test(timeout = 1)

Answer:  


@Timeout



Question 17

Which of the following is not a valid JUnit assertion?


assertEquals()  

assertNotNull()  

assertThrows()  

assertEmpty()

Answer:  


assertEmpty()



Question 18

Which JUnit 5 annotation is used to run a test multiple times?


@Repeat  

@RepeatedTest  

@LoopTest  

@TestRepeat

Answer:  


@RepeatedTest



Question 19

In TestNG, which annotation is used to indicate that a method should be executed before any test methods in the current class?


@BeforeTest  

@BeforeClass  

@BeforeMethod  

@BeforeSuite

Answer:  


@BeforeClass



Question 20

In Mockito, how can you mock a method to throw an exception?


when(methodCall).thenThrow(new Exception())  

doThrow(new Exception()).when(methodCall)  

throwException(new Exception()).when(methodCall)  

when(methodCall).throw(new Exception())

Answer:  


when(methodCall).thenThrow(new Exception())

Friday, July 12, 2024

Create a function that checks the connection status and reconnects if necessary

 const redis = require('redis');

const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { try { const pong = await pingAsync(); if (pong === 'PONG') { console.log('Redis connection is healthy'); } else { console.log('Unexpected response from Redis:', pong); await reconnect(); } } catch (err) { console.error('Redis connection error:', err); await reconnect(); } } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { client.quit(); client.connect((err) => { if (err) { console.error('Failed to reconnect to Redis:', err); reject(err); } else { console.log('Reconnected to Redis'); resolve(); } }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });


  1. Use the following code to check the connection and reconnect if necessary:

const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { try { const pong = await pingAsync(); if (pong === 'PONG') { console.log('Redis connection is healthy'); } else { console.log('Unexpected response from Redis:', pong); await reconnect(); } } catch (err) { console.error('Redis connection error:', err); await reconnect(); } } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { // Quit the current client client.quit(() => { // Create a new client instance const newClient = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client newClient.on('connect', () => { console.log('Reconnected to Redis'); resolve(newClient); }); newClient.on('error', (err) => { console.error('Failed to reconnect to Redis:', err); reject(err); }); // Replace the old client with the new client client = newClient; }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });




++++++++++++++++++++++++++++++++++++++++++++++++++++ 3. With timeout
const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) let client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Connection check timed out')); }, 5000); // 5 seconds timeout for the connection check pingAsync().then(pong => { clearTimeout(timeout); if (pong === 'PONG') { console.log('Redis connection is healthy'); resolve(); } else { console.log('Unexpected response from Redis:', pong); reconnect().then(resolve).catch(reject); } }).catch(err => { clearTimeout(timeout); console.error('Redis connection error:', err); reconnect().then(resolve).catch(reject); }); }); } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Reconnection timed out')); }, 10000); // 10 seconds timeout for reconnection // Quit the current client client.quit(() => { // Create a new client instance client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client client.on('connect', () => { clearTimeout(timeout); console.log('Reconnected to Redis'); resolve(); }); client.on('error', (err) => { clearTimeout(timeout); console.error('Failed to reconnect to Redis:', err); reject(err); }); }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });

FlushDB in Redis in node js

 const express = require('express');

const redis = require('redis'); const { promisify } = require('util'); const app = express(); const PORT = 3000; // Replace with your desired port // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `flushdb` method const flushdbAsync = promisify(client.flushdb).bind(client); // Function to flush the Redis database async function flushRedisDatabase() { try { const result = await flushdbAsync(); return { message: 'Database flushed successfully', result }; } catch (err) { console.error('Error flushing database:', err); throw err; } } // REST endpoint to flush the Redis database app.post('/flushdb', async (req, res) => { try { const response = await flushRedisDatabase(); res.status(200).json(response); } catch (err) { res.status(500).json({ error: 'Error flushing database', details: err.message }); } }); // Start the Express server app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); // Additional Redis client event handlers for better debugging client.on('connect', () => { console.log('Connected to Redis'); }); client.on('error', (err) => { console.error('Redis error:', err); }); client.on('ready', () => { console.log('Redis client ready'); }); client.on('reconnecting', () => { console.log('Reconnecting to Redis...'); }); client.on('end', () => { console.log('Redis connection closed'); });


Wednesday, July 10, 2024

Redis connection in node js

 import redis from 'redis';

// Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhost', // Replace with your Redis server host port: 6379, // Replace with your Redis server port retry_strategy: function (options) { // options.error contains the error object returned by the last attempt to connect if (options.error && options.error.code === 'ECONNREFUSED') { // If the connection was refused by the server, log the error and stop retrying console.error('The server refused the connection'); return new Error('The server refused the connection'); } // options.total_retry_time is the total time (in milliseconds) that the client has been trying to reconnect if (options.total_retry_time > 1000 * 60 * 60) { // If the total retry time exceeds 1 hour, log the error and stop retrying console.error('Retry time exhausted'); return new Error('Retry time exhausted'); } // options.attempt is the number of retry attempts so far if (options.attempt > 10) { // If the number of retry attempts exceeds 10, log the error and stop retrying console.error('Too many retry attempts'); return undefined; } // Reconnect after a specific time, which increases with each attempt // options.attempt * 100 gives a delay that increases by 100ms with each attempt // Math.min ensures the delay does not exceed 3000ms (3 seconds) return Math.min(options.attempt * 100, 3000); } }); // Event listener for successful connection client.on('connect', function() { console.log('Redis client connected'); }); // Event listener for errors client.on('error', function (err) { console.error('Something went wrong ' + err); }); export default client;

Redis connection in node js

 import redis from 'redis';

// Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhost', // Replace with your Redis server host port: 6379, // Replace with your Redis server port retry_strategy: function (options) { if (options.error && options.error.code === 'ECONNREFUSED') { // End reconnecting on a specific error and flush all commands with a individual error console.error('The server refused the connection'); return new Error('The server refused the connection'); } if (options.total_retry_time > 1000 * 60 * 60) { // End reconnecting after a specific timeout and flush all commands with a individual error console.error('Retry time exhausted'); return new Error('Retry time exhausted'); } if (options.attempt > 10) { // End reconnecting with built in error console.error('Too many retry attempts'); return undefined; } // Reconnect after a specific time return Math.min(options.attempt * 100, 3000); } }); client.on('connect', function() { console.log('Redis client connected'); }); client.on('error', function (err) { console.error('Something went wrong ' + err); }); export default client;

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > ...

Followers

Search This Blog

Popular Posts