During the solution of practical work, I created, for example, a code, a test module, both projects on version 4.8 Net, an XML file in it did an action when assembling the content and always copy, made a link to the object under test, but when running the test it gives an error: The test method UnitTestProjectXML.UnitTest1.UserManager_Add_FromXML created an exception:
System.NullReferenceException: The object reference does not point to an instance of the object..
Program code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XML_Unit_Test
{
public class UserValidator
{
public bool Add(string userId, string phone, string email)
{
if (userId.Length < 4)
throw new Exception("UserId должен быть больше 4 символов");
if (phone.Contains("a"))
throw new Exception("Телефон должен содержать только цифры");
if (!email.Contains("@"))
throw new Exception("Ошибка в email адресe");
// Логика сохранения данных
return true;
}
static void Main(string[] args)
{
}
}
}
The code of the unit test
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using XML_Unit_Test;
namespace UnitTestProjectXML
{
[TestClass]
public class UnitTest1
{
public TestContext TestContextInstance { get; set; }
private UserValidator validator = new UserValidator();
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"XMLFile1.xml",
"User",
DataAccessMethod.Sequential)]
[TestMethod]
public void UserManager_Add_FromXML()
{
string userID = Convert.ToString(TestContextInstance.DataRow["userId"]);
string telephone = Convert.ToString(TestContextInstance.DataRow["telephone"]);
string email = Convert.ToString(TestContextInstance.DataRow["email"]);
bool result = validator.Add(userID, telephone, email);
Assert.IsTrue(result, "Пользователь не может быть создан");
}
}
}
XML-code
<?xml version="1.0" encoding="utf-8"?>
<UserDetails>
<User userId="Dmitriy" telephone="+38 000 123 23 42" email="[email protected]"/>
<User userId="Ivan" telephone="+38 000 123 23 42" email="[email protected]"/>
<User userId="Alex" telephone="+38 000 123 23 42" email="[email protected]"/>
<User userId="Oleg" telephone="+38 000 123 23 42" email="[email protected]"/>
<User userId="Petro" telephone="+38 000 123 23 42" email="[email protected]"/>
<User userId="Roman" telephone="+38 000 123 23 42" email="[email protected]"/>
<User userId="Nikolay" telephone="+38 000 123 23 42" email="[email protected]"/>
</UserDetails>
Rename columns, did the full path to the file and just the name, provided that the XML file is in the unit test, changed from User to UserDetails, but nothing helped