Unit testing "object reference not set to an instance " at NUnit - nunit

i have a ASP.Net project and Nunitasp framework work for unit testing,i have a object in account.aspx.cs file when i tried to test the object(NugetplatformModel) value i get"object reference not set to an instance" error,
my account page code is given below
public partial class Account : System.Web.UI.Page
{
public NugetPlatformModel NugetPlatformModels;
public string result = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!WebSecurity.IsAuthenticated)
{
Response.Redirect("/login", true);
}
else
{
result = "success";
NugetPlatformModels = new NugetPlatformModel();
}
}
my test case code is given below
[Test]
public void AccountPage_ValidCredential_AccessModel()
{
Browser.GetPage(domain + "account");
string ExpectedPage = domain + "account";
logon();
Account acccountPage = new Account();
AssertEquals("success", acccountPage.result);
AssertEquals("should have license",true,acccountPage.NugetPlatformModels.IsHavingLicense);
}
How can I access and test that code behind variables? when start the testing the NUgetplatformmodel has been assigned i have checked it by debugging but after that in nunit gui it displays null reference error, i thought there is a problem in accessing variable in testcase..please help me..

It seems your code is not complete. From what I see here your account needs to run Page_Load in order to fill result and NugetPlatformModels. But I do not see how this method is launched in your test. Is it run from the constructor of Account?
It would be helpfull if you put all the code for Account in your post.

Related

Unity3d JsonUtility.FromJson() read from TextAsset works in app, fails in Test Runner

The following code works fine in my application (Unity 2019.3.0f6). It reads from Assets/Resources/lesson-text.json and writes the expected logs to the console:
// file to read lessons from
public TextAsset jsonFile;
internal JsonLessonList LoadLessonFromFile()
{
JsonLessonList testLessonList = JsonUtility.FromJson<JsonLessonList>(jsonFile.text);
foreach (JsonLesson lesson in testLessonList.jsonLessonList)
{
Debug.Log("Found lesson: " + lesson.Name);
}
return testLessonList;
}
I'm wanting to read the same file when using Unity's Test Runner:
[UnityTest]
public IEnumerator TestFileParsesOkTest()
{
JsonLessonList testLessonList = jsonReader.LoadLessonFromFile();
Assert.IsNotNull(testLessonList);
yield return null;
}
but I keep getting this exception:
TestFileParsesOkTest (0.019s)
Unhandled log message: '[Exception] NullReferenceException: Object reference not set to an instance of an object'. Use UnityEngine.TestTools.LogAssert.Expect
JsonReader.LoadLessonFromFile () (at Assets/Scripts/JsonReader.cs:68)
JsonReader.Start () (at Assets/Scripts/JsonReader.cs:37)
NullReferenceException: Object reference not set to an instance of an object
I know the file format is ok because it works from the app. I think the problem is that "TextAsset jsonFile" that is set through the unity editor is not being seen by the Test Runner. How do I make this work?
[Test]
public void JsonFileResourceTest()
{
Assert.IsNotNull(jsonReader.jsonFile);
}
results in:
JsonFileResourceTest (0.020s)
Expected: not null
But was: null
(The test driven development tag is because I got the very simplest read of a file with one field working, and now I want to back up and write a unit test for it and then write tests before coding going forward.)
I figured it out:
[SetUp]
public void Setup()
{
jsonReader = new GameObject().AddComponent<JsonReader>();
jsonReader.jsonFile = Resources.Load("lesson-test") as TextAsset;
}
// Verify class exists
[Test]
public void JsonReaderClassExists()
{
Assert.IsNotNull(jsonReader);
Assert.IsNotNull(jsonReader.jsonFile);
}

SpringBoot Test Cases not working in the way they were expected to

I have been working on a basic Spring Boot Application building REST APIs. I have learnt to write the APIs and now I am trying to write Unit Tests for them. I have written one unit test for the get API and one for the post API. The post API test seems to be running fine but the get api test fails. I am not sure why. I am not sure if the get test is running before the post and hence nothing is available so it fails?
I have tried changing the order in which the tests are written in order to see the execution order changes but it hasn't changed.
#RunWith(SpringRunner.class)
#WebMvcTest(value = ProjectRestController.class)
public class ProjectControllerTest
{
private String baseURL = "http://localhost:8080/";
private String expectedResult = "{id:0, name:\"Testing Course 0\", description: \"This is a test for course 0\"}";
#Autowired
private MockMvc mockMvc;
#MockBean
private ProjectService projectService;
Project mockProject = new Project(0, "Testing Course 0", "This is a test for course 0");
#Test
public void addProject() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.post(baseURL+"/projects")
.content(asJsonString(new Project(0, "Test 0", "Testing Project 0")))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
//This test does not seem to work. Returns 404
#Test
public void getProject() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get(baseURL+"/projects/0")
.accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
public static String asJsonString(final Object obj)
{
try
{
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
I expected a status 200 from the GET as the post is working fine however the get returns a 404.
The issue is due to you have a base URL you should not send the base URL, pass only /project/0

MSTest fails when I do run all, but works otherwise

So I have a Testclass using MSTest and every test works great if I run them one and one, however if I select 2 tests, namely can_register and cannot_Register_existing_username then the second fails (cannot_register_existing_username).
I have let my testclass inherit from an abstract class that looks like this:
public abstract class RollbackCapabilities
{
private TransactionScope _transactionScope;
[TestInitialize]
public virtual void TestInitialize()
{
_transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { Timeout = new TimeSpan(0, 10, 0) });
}
[TestCleanup]
public virtual void TestCleanup()
{
Transaction.Current.Rollback();
_transactionScope.Dispose();
}
}
If I comment this file out then it works (but now the data remains in the test-db which I don't want).
With this file above active the second test fails, the tests look like this
[TestMethod]
public void Can_Register()
{
//Arrange
AccountController ac = ControllerFactory.CreateAccountController();
RegisterModel model = new RegisterModel();
model.UserName = "TestUser";
model.Password= "TestPassword";
model.ConfirmPassword = "TestPassword";
//Act
ActionResult result = ac.Register(model);
//Assert
Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
Assert.AreEqual("Home", ((RedirectToRouteResult)result).RouteValues["controller"]);
Assert.AreEqual("Index", ((RedirectToRouteResult)result).RouteValues["action"]);
}
[TestMethod]
public void Cannot_Register_Existing_Username()
{
//Arrange
AccountController ac = ControllerFactory.CreateAccountController();
RegisterModel model = new RegisterModel();
model.UserName = "TestUser";
model.Password = "TestPassword";
model.ConfirmPassword = "TestPassword";
ac.Register(model);
RegisterModel model2 = new RegisterModel();
model2.UserName = "TestUser";
model2.Password = "OtherTestPassword";
model2.ConfirmPassword = "OtherTestPassword";
//Act
ActionResult result = ac.Register(model2);
//Assert
Assert.IsInstanceOfType(result, typeof(ViewResult));
Assert.AreEqual("", ((ViewResult)result).ViewName);
Assert.AreEqual(model2, ((ViewResult)result).ViewData.Model);
}
and finally the error i get is as follows:
Test method
Viducate.UnitTests.UserHandling.RegisterTests.Cannot_Register_Existing_Username
threw exception: System.Data.EntityCommandExecutionException: An
error occurred while executing the command definition. See the inner
exception for details. ---> System.Data.SqlClient.SqlException:
Invalid object name 'dbo.Users'.
Thats my problem, not big but very annoying and as mentioned if I run the tests one and one it works, it also works but leaves data in the db if I comment out my RollbackCapabilities class
Okay so I found out that my error was that I had created the database (but not tables) by hand because create database is not supported in multi-transaction.
however creating an empty database means that EF assumes there is tables already and that is why it failed with dont know what dbo.users are.
So what I did was created the tables as well and now it works. However this means I can never run this on a new development machine without first creating the tables and database. so annoying.
I think I will set up another test class that does not inherit my abstract rollback class and hade that create the tables permanently... should solve the problem as long as that runs first.

Where can I find the console or debug output from code executed in the package manager window?

I'm using EntityFramework code first with migrations. From the package manager console, I'm running "update-database". This executes Configuration.Seed(context) which I have overridden.
protected override void Seed(WebContext context)
{
Console.WriteLine("Console Test");
Debug.WriteLine("Debug Test");
Trace.WriteLine("Trace Test");
}
Where can I find that output?
Better yet, How do I output back to the package manager window?
Thx,
Dan
A quick hack I use to be able to quickly find a value in my Seed method is simply to throw an exception with a value I care about, e.g.
throw new Exception(yourValue);
This errors out the Seed, but my exception/value appears in my package manager console.
Where can I find that output?
Sorry, but the quick answer is basically nowhere.
To be precise at least not in the package manager console.
Debug.WriteLine("Debug Test");
Trace.WriteLine("Trace Test");
You can see the output of the Debug... and Trace... methods if you attach another Visual Studio to debug the Visual Studio instance which is running the update-database command. Then in the debuggin VS you can see the output in the Output Window.
Console.WriteLine("Console Test");
You can see the output of the Console... methods if you run the migrations with the
migrate.exe command line tool which comes with EF:
How do I output back to the package manager window?
I have here also bad news, after a quick "reflectoring": with the current implementation of the EF migrations it's not supported to display custom information during execution of the update-database (or any other command).
Running a SQL print command will write to the Package Manager Console. Here is a helper method that I use:
/// <summary>
/// write a message to the Package Manager Console
/// </summary>
public void Debug(string s, params object[] args)
{
var fullString = string.Format(s, args).Replace("'", "''");
Sql(string.Format("print '{0}'", fullString));
}
My needs were similar to yours so I figured I'd document them here in case they could help someone else out. My goal was to display all of the output from the migrations including all of the sql run as part of the Seed method. As a side effect of this solution, you will also be able to see any Debug.Write message in your code.
First create a DebugMigrationsLogger that will write all migration output to Debug.WriteLine (thanks to http://whiteknight.github.io/2013/01/26/efcodeonlymigrations.html):
public class DebugMigrationsLogger : System.Data.Entity.Migrations.Infrastructure.MigrationsLogger
{
public override void Info(string message)
{
Debug.WriteLine(message);
}
public override void Verbose(string message)
{
Debug.WriteLine(message);
}
public override void Warning(string message)
{
Debug.WriteLine("WARNING: " + message);
}
}
Next make sure you have a subclass of DbMigrationsConfiguration for your DbContext:
public class MyDbMigrationsConfiguration : DbMigrationsConfiguration<MyDbContext>
{
public MyDbMigrationsConfiguration()
{
}
protected override void Seed(MartusDb db)
{
//...
}
}
Next you run your migrations as an on-demand unit test so your test runner can capture the output. My unit test looks something like this:
public void MigrateDb_Test()
{
var config = new MyDbMigrationsConfiguration { AutomaticMigrationDataLossAllowed = true };
var migrator = new DbMigrator(config);
var loggingDecorator = new MigratorLoggingDecorator(migrator, new DebugMigrationsLogger());
loggingDecorator.Update();
}
Lastly, set the Database.Log in your DbContext constructor:
public class MyDbContext : DbContext
{
public MyDbContext()
{
Database.Log = message => Debug.WriteLine(message);
}
}
Now whenever you run the MigrateDb_Test() you will see all the output, it has made debugging migrations so much easier for me!
Dirty workaround extending George's answer.
protected override void Seed(YourContext context)
{
using (var seedout = new StringWriter())
{
// do your work
context.Authors.AddOrUpdate(x => x.Id,
new Author() { Id = 1, Name = "Jane Austen" }
);
// some message
seedout.WriteLine("some message");
// commit your work
context.SaveChanges();
seedout.WriteLine("Seed successfully completed.");
// dummy exception to show message on package manager console
throw new Exception(seedout.ToString());
}
}

RIA Services EntitySet does not support 'Edit' operation

Making my first steps in RIA Services (VS2010Beta2) and i encountered this problem:
created an EF Model (no POCOs), generic repository on top of it and a RIA Service(hosted in an ASP.NET MVC application) and tried to get data from within the ASP.NET MVC application: worked well.
Next step: Silverlight client. Got a reference to the RIAService (through its context), queried for all the records of the repository and got them into the SL application as well (using this code sample):
private ObservableCollection<Culture> _cultures = new ObservableCollection<Culture>();
public ObservableCollection<Culture> cultures
{
get { return _cultures; }
set
{
_cultures = value;
RaisePropertyChanged("cultures");
}
}
....
//Get cultures
EntityQuery<Culture> queryCultures = from cu in dsCtxt.GetAllCulturesQuery()
select cu;
loCultures = dsCtxt.Load(queryCultures);
loCultures.Completed += new EventHandler(lo_Completed);
....
void loAnyCulture_Completed(object sender, EventArgs e)
{
ObservableCollection<Culture> temp=
new ObservableCollection<Culture>loAnyCulture.Entities);
AnyCulture = temp[0];
}
The problem is this: whenever i try to edit some data of a record (in this example the first record) i get this error:
This EntitySet of type 'Culture' does not support the 'Edit' operation.
I thought that i did something weird and tried to create an object of type Culture and assign a value to it: it worked well!
What am i missing? Do i have to declare an EntitySet? Do i have to mark it? Do i have to...what?
Thanks in advance
It turns out that in the DomainService class one has to implement (or at least to mark "placeholder methods") as "Edit", "Delete",... eg
[Delete]
public void DeleteCulture(Culture currentCulture)
{
throw new NotImplementedException("UpdateCulture not Implemented yet");
}
[Insert]
public void InsertCulture(Culture newCulture)
{
throw new NotImplementedException("InsertCulture not Implemented yet");
}
This way the OrganizationDomainContextEntityContainer class creates an EntitySet with parameter EntitySetOperations.All (meaning that all the CUD operations are available).
Hope it's useful for someone in the future!