how do you mock an xml for unit testing?

qinking126

I need to unit testing this GetData method.

    public MessageResponse GetData(XmlElement requestElement)
    {   
        MessageResponse MsgResponse = new MessageResponse();


        if (requestElement.Attributes["employeeNo"] == null){
            MsgResponse.Messages = new List<string>();
            MsgResponse.Messages.Add("Attribute employeeNo is missing");
            MsgResponse.Error = true;
            return MsgResponse;
        }
        if (requestElement.Attributes["xmlEmployeeName"] == null){
            MsgResponse.Messages.Add("Attribute xmlEmployeeName is missing");
            MsgResponse.Error = true;
            return MsgResponse;
        }
        return MsgResponse;
    }

this method needs a XmlElement parameter. how do I mock it? in my code, I first created a xmlDocument, then load the xml file.

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFilePath);
            requestElement = doc.DocumentElement;

for me to test it, first i need to create a xml file without employeeNo, the create antoher one without name, maybe alot more for other scenarios. it just seems like alot work. is there a better way to test it?

should I use moq or other testing framework to simplify the testing?

Sunny Milenov

You can just create the element you want to test with, w/o reading a file at all:

var doc = new XmlDocument();
doc.LoadXml("<MyTestElement/>");
var myTestElement = doc.DocumentElement;
myTestElement.Attributes["employeeNo"] = "fakeId";

var response = myTestResponder.GetData(myTestElement);

//assert whatever you need to

NOTE: every time you find out that the test is too hard to write, usually this means that your class/method does too much.

I would assume, that your method verifies the input, than does something with the data provided. I would suggest that you abstract the data reading part (using some xml deserializer) to populate the data model you need for your application.

Then run validation on the result of the deserialized data. Something like:

public MessageResponse GetData(XmlElement requestElement)
{
   var data = _xmlDeserializer.Deserialize(requestElement);
   var validationResult = _validator.Validate(data);
    if (validationResult.Errors.Count > 0)
    {
         //populate errors
        return result;
    }

    _dataProcessor.DoSomethingWithData(data);
}

Take a look at FluentValidation for a nice validation library.

If you go the above route, then your tests will be much simpler.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do you mock out the file system in C# for unit testing?

How do I create a mock context for grpc unit testing (python)

How do you Mock LUIS during Unit Tests?

How do you mock a return value from PyMySQL for testing in Python?

How do you await a Task when unit testing?

How do you know which components to import when unit testing?

How to do unit testing

How to mock an interface in Unit Testing in Java?

How to mock mongodb for unit testing graphql resolver

How to mock a buffered file handle for unit testing

How to mock LocalCache in unit testing with Mockito

How to mock a web server for unit testing in Java?

How to mock "this" keyword in Jest Unit Testing

How to Mock REST API in unit testing?

how to mock an alert in unit testing of angular

How to provide mock filters for unit testing

How to mock LDAP Laravel auth for unit testing

How Mock JsonReader unit testing a custom JsonConverter

How do you mock classes that are used in a service that you're trying to unit test using JUnit + Mockito

How to mock a tornado coroutine function using mock framework for unit testing?

How do I mock a realine of a GLOB ref when unit testing in perl?

How do i mock the behavior of a void method when unit testing my delete service?

When unit testing, how do I mock a return null from async method?

How do I mock a "with connect" SQL query in a Python 3 unit testing?

Unit testing Mock GCS

How to do Unit Testing with gorm

How do you mock an IAsyncEnumerable?

Grails 3 Unit Testing: How do you do mockFor, createMock, and demands in Grails 3?

How do you mock the Firebase SDK when testing action creators in Redux?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive