How to Configure macOS for iOS Mobile App Automation using Appium?

How to Configure macOS for iOS Mobile App Automation using Appium?

iOS App Automation on macOS – Configuring a macOS system for testing on real iOS devices for mobile app automation is a lengthy and complicated process. The steps to follow for this configuration are tricky, and many times testers struggle with it.

The steps involved are installing the right software, setting environment variables, configuring settings on the device, and connecting the devices properly for iOS app automation. This can cause lots of issues in configuration and slow down the testing process.

In this blog, we’ll make this process easy for you to follow.

We’ll walk you through each step, from installing necessary software like the Java Development Kit (JDK) and Xcode, to setting up your iOS device for iOS app automation on macOS.

We’ll also show you how to install Appium, configure it correctly, and use tools like Appium Inspector to interact with your app.

By following this simple guide, you’ll be ready to test your mobile apps on real devices quickly and efficiently for iOS app automation on macOS.

What is Appium testing in iOS App Automation on macoS

Appium is a freely distributed open-source automation tool used for testing mobile applications. It allows testers to automate native, hybrid, and mobile web applications on iOS and Android platforms using the WebDriver protocol. 

Appium provides a unified API (Application Programming Interface) that allows you to write tests using your preferred programming language (such as Java, C#, Python, JavaScript, etc.) and test frameworks. It supports a wide range of automation capabilities and handling various types of mobile elements.
Appium enables cross-platform testing, where the same tests can be executed on multiple devices, operating systems, and versions, providing flexibility and scalability in mobile app testing or iOS testing. It has NO dependency on Mobile device OS; because APPIUM has a framework or wrapper that translates Selenium WebDriver commands into UIAutomation (iOS) or UIAutomator (Android) commands depending on the device type, not any OS type.

Prerequisites for iOS Automation Setup on macOS

  1. JDK Installation 
  2. Install npm and Node.js 
  3. Install Appium Server & Appium Inspector 
  4. Setting up environment variables
  5. Xcode installation and setup
  6. Install XCUITest Driver
  7. Install WebDriverAgent 
  8. Real Device Settings
  9. Get the device-identifier or udid of real device
  10.  Configure the desired capabilities of Appium Inspector
  • 1. JDK Installation:
    Download and Install JAVA JDK for MAC OS (https://www.oracle.com/in/java/technologies/downloads/#jdk21-mac)
    If already installed on the system, please check and confirm using command-
    • java -version
  • 2. Install npm and Node.js:
    Download the Node.js pre-built installer for mac platform and install it. (https://nodejs.org/en/download) If already installed on the system, please check and confirm using the following commands on the terminal.
    • To see if Node is installed, type in node -v .
    • To see if NPM is installed, type in npm -v  
  • 3. Install Appium Server & Appium Inspector:
    Install the Appium via terminal you need to run the below commands:
  • 4. Setting up environment variables:
    Do below settings in .profile file. Open a terminal and type following command-
    • nano ~/.profile
    • Then, paste the below commands: (Change your username!).
    • export JAVA_HOME=$(usr/libexec/java_home)
    • export PATH=$JAVA_HOME/bin:$PATH
  • 5. Xcode installation and setup:
    You can download Xcode from the App Store (https://apps.apple.com/us/app/xcode/id497799835?mt=12 ) to install the command line tools use following command in terminal-
    • xcode-select — install
    • Open Xcode a Preferences -> Accounts -> Add Apple ID
  • 6. Install XCUITest Driver:
    Now we need to install XCUITest driver which allows to interact with the UI elements of iOS apps during automated testing. Use following command in terminal to install XCUITest driver-
    • appium driver install xcuitest
  • 7. Install WebDriverAgent:
    Open Terminal & Run the following command:
    • cd /Applications/Appium-Server-GUI.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitestdriver/appium-webdriveragent
    • To make directory in Resources folder mkdir -p Resources/WebDriverAgent.bundle

How to setup WebDriverAgent on Mac for iOS App Automation

WebDriverAgent is a WebDriver server implementation for iOS that can be used to remote control iOS devices. We need to add an account to XCode (you can use your Apple Id or create new).

For that go to XCode —> Preferences —> Accounts

setup for iOS app automation

Once you are signed in — your account will appear at the left.

We need to add Signing Certificate to this account iOS Automation:

1. Click on Download Manual Profiles
2. Click on Manage Certificates — Plus icon — Apple Development. Once it is done — you will see a new certificate added to the list as per screenshot below

iOS automation account

Open the WebDriverAgent.xcodeproj project in xcode

To find it please use the path:
/Applications/Appium-Server-GUI.app/ Contents/ Resources/ app/node_modules /appium/node_modules/appium-xcuitestdriver/appium-webdriveragent

(NOTE: If you do not see this folder — please use shortkeys “Shift”+”Command”+”.” to display hidden files in your Macintosh HD root)

Click on Project name at the left navigation (WebDriverAgent)

For both the WebDriverAgentLib and WebDriverAgentRunner targets, Go to Signing & Capabilities and Select the Automatically Manage Signing check box select your development team and Select your device. This should also auto select Signing Certificate. The outcome should look as shown below:

automation project in xcode

If the error below appears while changing the Bundle Identifier, we will need to change the  value of Bundle Identifier to something else which xCode can accept.

error in setup

The value for Bundle Identifier should be changed in the following places:

  1. WebDriverAgentLib target:
    • From the Signing & Capabilities tab —change value of Bundle Identifier
    • From Build Settings tab — Packaging section — change value of Product Bundle Identifier
  2. WebDriverAgentRunner target:
    • From Build Settings tab — Packaging section — change value of Product Bundle Identifier
  3. IntegrationApp target:
    • From the Signing & Capabilities tab — change value of Bundle Identifier
    • From Build Settings tab —> Packaging section —> change value of Product Bundle Identifier

After changing the values of Bundle Identifier,
Build the WebDriverAgentLib, WebDriverAgenrRunner, IntegrationApp from WebDriverAgent project in xcode.

  • 8. Now for real device testing
    • we also need to make some changes on device side too so we need to enable  developer option for this:
    • Open settings and click on Privacy and Security-> Developer Option:
real device ios automation
pop-up
  • 9. Get the device-identifier or udid of real device
    • Once the xcode build is succeeded and Developer mode of device is turned on, get the udiid or device-identifier connected to the mac machine from xcode as well as get the bundleId.
    • xcode- windows-Devices and Simulators – check the identifier and other device details, which are required to define capabilities to connect to device either programmatically or through Appium inspector.
device identifier

Get the bundleId from xcode-

  • A bundle ID, also known as a CFBundleIdentifier. It is a unique identifier for an app in Xcode, allowing the system to distinguish it.
  • Bundle IDs are typically written in reverse-DNS format and can only contain alphanumeric characters (A–Z, a–z, and 0–9), hyphens (-), and periods (.). They are also case-insensitive.
  • BundleId is required to define capabilities to connect to the device either programmatically or through Appium inspector.
    For that, from xcode, select the top project item in the project navigator at the left then select TARGETS -> General. Bundle Identifier is found under Identity.

After all the settings, you need to build the xcode project from the Terminal – for that we need to run the following command:
(xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination ‘id=udid’ test ) from the location where the WebDriverAgent project is present. To go to that location first run the command-

cd /Applications/Appium-Server-GUI.app/Contents/Resources/app/node_modules/appium/node_modules/appiumxcuitestdriver/appiumwebdriveragent

Now run the command with device identifier and WebDriverAgent project location.

(e.g. –
xcodebuild -project /Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appiumxcuitestdriver/appiumwebdriveragent/WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination ‘platform=iOS,id=53e4089fac10d5307c8f0d9a1f35aeb84e89b819’ test)

After the above configurations, Start Appium Server from the terminal.
Start Appium Inspector and set the desired capabilities.

  • 10. Configure the desired capabilities and other settings of Appium Inspector:

Appium inspector is a tool which provides testers with a graphical user interface  for inspecting and interacting with elements within mobile applications.When setting up automation with Appium for ios devices, it’s crucial to define the desired capabilities appropriately. These capabilities act as parameters that instruct Appium on how to interact with the device and the application under test.

Open the Appium Inspector and enter Remote Host as 0.0.0.0 and Remote Port as 4723. and set the following parameters as desired capabilities:

appium parameters for ios automation
  • deviceName: This parameter specifies the name of the testing device. It’s essential to provide an accurate device name to ensure that Appium connects to the correct device. 
  • udid: The Unique Device Identifier (UDID) uniquely identifies the device among all others. Appium uses this identifier to target the specific device for automation. Make sure to input the correct UDID of the device you intend to automate. 
  • platformName: The platform name is set to “iOS,” indicating that the automation targets the iOS platform.
  • platformVersion: This parameter denotes the version of the ios platform of the device. 
  • automationName: Appium supports multiple automation frameworks, and here, “XCUITest” is specified as the automation name. XCUITest is a widely used automation framework for testing iOS apps. 
  • bundleId: This unique identifier for an app in Xcode allows the system to distinguish it.

Once you set all the above capabilities, click the Start Session button to open the application in Appium Inspector with the specified capabilities. Your app is now ready for inspection to prepare for efficient automation testing.

automation testing

also you can see the following image on your device’s screen:

Automation running

Conclusion

Setting up Appium for testing on real iOS devices can initially seem complicated due to the numerous steps involved and the technical nuances of configuring software and environment variables. However, by following this step-by-step guide, the process becomes easy and manageable.

Having the right tools and configurations in place streamlines your testing workflow, ensuring efficient and effective testing of your mobile apps on real devices. This not only improves the quality of your apps but also enhances your overall development process.

Remember, the key to successful automation testing is meticulous setup and configuration. By taking the time to follow each step carefully, you will save yourself from potential issues down the line and make your testing process smoother.

Click here to read more blogs like this.

How to implement Page Object Model (POM) using C# with Selenium

How to implement Page Object Model (POM) using C# with Selenium

Introduction:

Selenium is an open-source Web UI automation testing suite/tool. It supports automation across different browsers, platforms, and programming languages which includes Java, Python, C#, .net, Ruby, PHP, and Perl, etc. for developing automated tests. Selenium can be easily deployed on Windows, Linux, Solaris, and Macintosh Operating Systems. It also provides support for mobile applications like iOS, windows mobile, and Android for different Operating Systems.

Selenium consists of drivers specific to each language. Additionally, the Selenium Web driver is mostly used with Java and C#. 

Test scripts can be coded in selenium in any of the supported programming languages and can be run directly in most modern web browsers which include Internet Explorer, Microsoft Edge, Mozilla Firefox, Google Chrome, Safari, etc.

Furthermore, C# is an object-oriented programming language derived from C++ and Java.
It supports the development of console, windows, and web-based applications using Visual Studio IDE on the .Net platform.

With Selenium C#, there is a wide variety of automation frameworks that can be used for automated browser testing. Each framework has its own advantages and disadvantages, they are chosen on the basis of their requirement, compatibility, and the kind of solution they’d prefer. These are the most popular Selenium C# frameworks used for test automation.

NUnit:

It is a unit testing tool ported initially from JUnit for .Net Framework and is an Open Source Project. NUnit was released in the early 2000s, though the initial Nunit was ported from Junit, the recent .Net version 3 is completely rewritten from scratch.

To run the Nunit test we need to add attributes to our methods. An example, attribute [Test], Indicates the Test method. Below are the NuGet Packages required by NUnit

NUnit
NUnit3TestAdapter
Microsoft.NET.Test.Sdk 

XUnit:

XUnit is a unit testing tool for .Net Framework which was released in 2007 as an alternative to Nunit. xUnit has attributes for the execution of tests but is not similar to NUnit. [Fact] and [Theory] attributes are similar to [Test] 

Below are the NuGet Packages required by xUnit

Xunit
Xunit. runner.VisualStudio
Microsoft.NET.Test.Sdk

MSTest:

MSTest is a unit testing framework developed by Microsoft and ships with Visual Studio. However, Microsoft made version 2 open-source which can easily be downloaded. Additionally, MSTest has an attributes range similar to NUnit and provides a wide range of attributes along with parallel run support at the Class and Method level.

Prerequisite:

To get started with Selenium C# and the Page Object Model framework, first, we need to have the following things installed.

1) IDE: Download and install any IDE of your choice.

  •  Here we are using Microsoft Visual Studio 2022
  •  After downloading the Visual Studio Installer, select the .NET desktop development option and then click on Install.
  •  Now let the Visual Studio Installer download the packages and perform the installation.
  •  Install the latest version of the .NET Framework on your machine.

2) Create New Project: After the installation is over, begin using Visual Studio.

  •  select the Create a new project option, then select the xUnit Test Project option for C#.

3) Selenium Webdriver for Chrome Browser: You must also install Selenium’s web driver for Chrome browser.

  •  In Visual Studio navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.
  • In the Search Bar, enter the name of the packages you want to install (e.g. Selenium .WebDriver).
  • Check the Project checkbox, and click on Install.
  • In the dialogue box asking to accept the licences click on Accept button.
  • This will start the installation process and install the Selenium WebDriver.

Selenium.WebDriver

This package contains the .NET bindings for concise and object-based

Selenium WebDriver API, which uses native OS-level events to manipulate the browser,
Selenium.Chrome.WebDriver (chrome driver exe)
This NuGet package installs Chrome Driver (Win32) for Selenium WebDriver in your xUnit Test Project.


Once Visual Studio is finished with the successful installation of the Selenium WebDriver, it will show a message in the output window.
Once the Visual Studio is set up with all dependencies, it’s ready for work.

Note: We will be using the demo testing website (https://www.calculator.net/) and trying to achieve the addition and subtraction operations for our automation test.

Writing the First Selenium C# Test:

Download the WebDriverManager from Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.

WebDriverManager is an open-source Java Library that automates the management of driver executables required by Selenium WebDriverby performing the four steps (find, download, setup, and maintenance) for the drivers required for Selenium tests. Here are some benefits of WebDriverManager in Selenium:

  • WebDriverManager automates the management of WebDriver binaries, thereby avoiding installing any device binaries manually.
  • WebDriverManager checks the version of the browser installed on your machine and downloads the proper driver binaries into the local cache (~/.cache/selenium by default) if not already present.
  • WebDriverManager matches the version of the drivers. If unknown, it uses the latest version of the driver.
  • WebDriverManager offers cross-browser testing without the hassle of installing and maintaining different browser driver binaries.

In the UnitTest1 file, the final code looks like this:

public class UnitTest1
    {
        IWebDriver driver;
        CalculatorPage calc_page;
        public void Initialize_driver()
        {
         new WebDriverManager.DriverManager().SetUpDriver(new ChromeConfig());
            driver = new ChromeDriver();
          calc_page = new CalculatorPage();
        }
        public void Close_driver()
        {
        driver.Close();
        }
       [Fact]
        public void Add()
        {
            initialize_driver();
            calc_page.Initialize(driver);
            string actualresult = calc_page.calculate("14", "+", "5");
            Assert.Equal("19", actualresult);
            Close_driver();
        }
        [Fact]
        public void Subtract()
        {
            initialize_driver();
            calc_page.Initialize(driver);
            string actualresult = calc_page.calculate("24", "-", "5");
            Assert.Equal("19", actualresult);
           Close_driver()
        }
    }

Now just build your code by right-clicking the project xUnitTestProject1 or by pressing Ctrl + Shift + B and you will be able to see your test in “Test Explorer”.

After following the above procedure, run the test case. But this code will not execute unless the Chrome driver for the Selenium is not downloaded and unzipped on the system.

When developing a scalable and robust automation framework, it is important to consider the following challenges:

  1. Keeping up with UI changes: The primary goal of automated UI web tests is to validate the functionality of web page elements. However, the UI is subject to constant evolution, leading to changes in web locators. These frequent changes in web locators pose a challenge to code maintenance.
  2. Code maintenance: With the ever-changing UI, it is crucial to maintain the automation codebase effectively. Failing to update Selenium test automation scripts to reflect changes in web locators can result in test failures. Proper maintenance is essential to ensure the longevity and reliability of the test scripts.
  3. Test failure due to lack of maintenance: Inadequate maintenance of automation scripts can lead to scenarios where tests fail. One common cause is a change in web locators. If the Selenium test automation scripts are not updated accordingly, it can cause a significant number of tests to fail, impacting the overall test suite’s reliability.

So to address this, restructure the Selenium test automation scripts for increased modularity and reduced code duplication.

Utilizing the Page Object Model (POM) design pattern achieves code restructuring and minimizes the effort required for test code maintenance.

Now, let’s delve into a comprehensive overview of the Page Object Model, including the implementation and effective maintenance of your Selenium test automation scripts.

Why do we need Page Object Model in Selenium C#?

Selenium test automation scripts become more complex as the web applications add more features and web pages. With every new page added, new test scenarios are included in the Selenium test automation scripts. With this increase in lines of code, its maintenance can become very tedious and time-consuming. Also, the Repetitive use of web locators and their respective test methods can make the test code difficult to read.

Instead of spending time updating the same set of locators in multiple Selenium test automation scripts, a design pattern such as the Page Object Model can be used to develop and maintain code.    

What is Page Object Model In Selenium C#?

Page Object Model is the most widely used design pattern by the Selenium community for automation tests in which each web page (or significant ones) is considered as a separate class and a central object repository is created for controls on a web page.

  • Each Page Object (or page classes) contain the elements of the corresponding web page along with the necessary methods to access the elements on the page.
  • Thus it is a layer between the test scripts and UI and encapsulates the features of the page.
  • The Selenium test automation scripts do not interact directly with web elements on the page, instead, a new layer (i.e. page class/page object) resides between the test code and UI on the web page.  
  • Hence, Selenium test automation implementation that uses the Page Object Model in Selenium C# will constitute different classes for each web page thereby making code maintenance easier.
  • In complex test automation scenarios, automation scripts based on Page Object Model can have several page classes (or page objects). It is recommended that you follow a common nomenclature while coming up with file names (representing page objects) as well as the methods used in the corresponding classes. For example, if automation for a login page & dashboard page is to be performed, our implementation will have a class each for login & dashboard. The controls for the login page are in the ‘login page’ class and the controls for the dashboard page are in the ‘dashboard page’ class.


How to Use Page Object Model:

We will now implement the Page Object Model for the use case we considered above i.e. trying to achieve the addition and subtraction operations for our automation test on the Calculator page.
Create a class file – CalculatorPage.cs for Calculator page operation. This page class contains the locator information of the elements on that page. Also, we need to define the methods for that page in the CalculatorPage.cs class and call the methods from UnitTest1.cs.


We are initializing the Chromedriver object and launching the web page from the initialiseDriver() method from UnitTest1.cs. Also, we are creating the instance of CalculatePage from the same method.
The CalculatePage.cs contain an instance of IWebDriver and the following methods –

Initialize(): this method takes one IWebDriver object as an input parameter and it is assigned to a locally defined IWebDriver object. Also, the required web page is launched using this driver.

Calculate(): this method is actually used to do the calculation operation of two numbers..either addition or subtraction using 3 input parameters as user input number value1, number value 2, and operator like -’+’ or ‘-’. The required elements from the page are located and as per the operator, the required operation is performed on those.
The final code of CalculatePage.cs would look like the below:

public class CalculatePage
    {
        IWebDriver driver;

        public void Initialize(IWebDriver driver)
        {
            this.driver = driver;          
            driver.Navigate().GoToUrl("https://www.calculator.net/");
        }
       
    public string Calculate(string no1, string op, string no2)
        {
            IWebElement number1;
            char[] ch = no1.ToCharArray();

            for (int i = 0; i < no1.Length; i++)
            {
                number1 = driver.FindElement(By.XPath("//span[@onclick='r(" + ch[i] + ")']"));
                number1.Click();
             }

            IWebElement op_element = driver.FindElement(By.XPath("//span[@onclick=\"r('" +op + "')\"]"));
            op_element.Click();
            ch = no2.ToCharArray();

            for (int i = 0; i < no2.Length; i++)
            {
                number1 = driver.FindElement(By.XPath("//span[@onclick='r(" + ch[i] + ")']"));
                number1.Click();
            }
            IWebElement result = driver.FindElement(By.Id("sciOutPut"));
            string actual_result = result.Text.Trim();
            return actual_result;
      }
   }

Advantages of Page Object Model in Selenium C#:

Page Object Model is a widely used design pattern nowadays. It reduces code duplication, enhances code readability, and improves maintainability by emphasizing reusability and extensibility.
Furthermore, below are some of the major advantages of using the Page Object Model in Selenium C#.

Better Maintenance – With separate page objects (or page classes) for different web pages, functionality or web locator changes will have less impact on the change in test scripts. This makes the code cleaner and more maintainable as Selenium test automation implementation is spread across separate page classes.

Minimal Changes Due To UI Updates – The effect of changes in the web locators will only be limited to the page classes, created for automated browser testing of those web pages. This reduces the overall effort spent in changing test scripts due to frequent UI updates.

Reusability – The page object methods defined in different page classes can be reused across Selenium test automation scripts. This, in turn, results in a reduction of code size as there is increased usage of reusability with the Page Object Model in Selenium C#.

Simplification –One more important point of using this design pattern is that it simplifies the visualization of the functionality and model of the web page as both these entities are located in separate page classes. 

Execution:

Navigate to Test -> Run All Tests.
This will launch the test explorer in Visual Studio and will run our test. 

You can run the test from the command prompt or visual studio’s terminal (Developer Command Prompt) with the following command-

dotnet test

This dotnet test command is used to run the tests in the project in the current directory. The dotnet test command builds the solution and runs a test host application for each test project in the solution. While running the tests from the project, you can put different filters while running the test, like running the tests with particular tags, from specific projects, with particular names, etc.

You can find this framework in the following Git Repository.

spurqlabs/CSharp-Selenium-Page-Object-Model (github.com)

Conclusion:

Implementing the Page Object Model in Selenium with C# provides a structured approach to automation testing, making the code more maintainable and reusable. It simplifies the handling of UI changes and enhances the overall efficiency of the testing process for large-scale applications.

Read more blogs here

Easy way to verify the MD5 checksum of a downloaded file in Test Automation

Easy way to verify the MD5 checksum of a downloaded file in Test Automation

There are many instances during test automation when you would download the files and then would want to verify the completeness of your files downloaded. The MD5 checksum verification is to validate the authenticity of the file so we can ensure that the received file is exactly the same as at the source. This blog explains what MD5 checksum is and also, how we can use it in test automation.

Let’s understand the need for MD5 checksum Verification for a file.

Different kinds of files are distributed on the network or any storage media at different destinations. So, there is a chance that the file can be corrupted because of a few missing bits during data transfer due to some different reasons. Below are a few factors that can cause this to happen, such as:

  •    An interruption to the Internet or network connection.
  •    Storage or space problems, including hard drive-related problems.
  •    A corrupted disk or corrupted file.
  •    A third party interfering with the transfer of data.

After receiving the file, we need to check if the file received is correct or incorrect. It also becomes necessary to verify that our copy of the file is authentic and does not contain any error by applying some sort of test.

We basically use the special key string for this file integrity test known as a checksum. Also, we can refer to checksum as a hash sum or a hash value, hash code, or simply a hash. The most famous and widely used checksum technique is nothing but the MD5 checksum.

the digest, MD5, or hash checksum has been extensively used in the software world to provide some assurance that an uploaded file arrived intact from its source

What is MD5?

The message-digest algorithm(MD5) is a cryptographic hash function whose main purpose is to verify that a file has not been altered.

MD5 hashes are 128 bits long and are usually displayed as their 32-digit hexadecimal equivalents. It doesn’t matter how large or small the file or text is.

For Reference:https://www.intel.com/content/www/us/en/support/programmable/articles/000078103.html

What is the MD5 checksum of a file?

As we learn, it is a 32-character hexadecimal number that is computed on a file. Various Checksum programs are used to generate checksum key strings from the files and verify the integrity of the files. Later by using that checksum string with the original ones shared by the file servers. The file servers often provide a pre-computed MD5, so that a user can compare the checksum of the downloaded file to it. There is a high probability that two files with the same MD5 checksum are the same.

How to calculate MD5 checksum for a file:

1. Calculate MD5 checksum for a file for windows:

With a command prompt, PowerShell command, or third-party applications like Hash Generator or MD5 Checksum Utility, you can generate a checksum for a file. 

a. With the command prompt:

Basically, the command line tool is built-in into the Microsoft Windows 10 operating system, as a certificate service, which is “CertUtil”.

This command line offers a switch, “Hashfile”; We can generate a hash string. Here is a specific algorithm that we can use, such as MD5:

certutil -hashfile <file> <algorithm>           

certutil -hashfile Example.txt MD5

It generates an MD5 file checksum in the command prompt on Windows…

b. With PowerShell:

Since there is no coding, this is the most efficient and easiest method. If PowerShell 4.0 is used then a command line, i.e., cmdlet exists in it.

 This cmdlet can also reffer as “Get-FileHash”. Thanks to this command line, because of that command line we can generate hash files easily:

Get-FileHash -Path <file> -Algorithm <name>

Get-FileHash -Path explorer.exe -Algorithm MD5

Use Get-FileHash in Powershell. It returns the hexadecimal string/hash.

2. Calculate MD5 checksum for a file using some Third Party Tools:

Also, you can find out which tools to use in the right-click menu in a file. Following are some tools we generally can use:

·        Hash Generator

·        MD5 & SHA Checksum Utility.

·      HashMyFiles 

3. Calculate MD5 checksum for a file through automation using C# :

Here, you can calculate programmatically using .net, Java, Python, etc.

To calculate it for a file in C#, .net provides an inbuilt functionality for generating these hash functions, For that reason, we need to import the following NuGet package: https://www.nuget.org/packages/Security.Cryptography

System.Security.Cryptography.MD5

Firstly we need to instantiate the Message Digest Object.

The Compute Hash method of the instance returns the computed hash of the file (bypassing the file stream).

Later, we can convert it to hex, the Bit Converter allows you to represent it as a string for conversion.

So, below is an example code showing a method (GetMD5HashFromFile ()).

It accepts the file name along with the path and then returns the calculated checksum. Also, generates the checksum, After that, it converts into a hex string, and removes dashes. This is the typical format.

The hash string for the file returned by this method can be compared with the one provided by the file servers and checked if the file is altered or not.

private string GetMD5HashFromFile(string fileName)
       using (var md5 = MD5.Create())
       {
                using (var stream = File.OpenRead(fileName))
                 {
                       var hash= md5.ComputeHash(stream);
                      return BitConverter.ToString(hash).Replace("-", string.Empty);
              }
         }

You can call the above function wherever you need to get the checksum. For example:

void verifyChecksum()
{
string filePath = "../../../Resources/test.pdf";
string hash = GetMD5HashFromFile (filePath);
Assert.Equal("A152F13B6EE1EA3D047A6AB99D12A1A1", hash);
}

Conclusion:

As I have implemented and tested this in a test case automation, so, I believe this is a most simple and easier way to verify MD5 checksums for a file in automation using C#

Read more blogs here