I have the following method in a class...
public Boolean isMemberOf(string user, int league) {
Boolean isPlayer = false;
var leaguePlayer = db.GameworldPlayers.Count();
if (leaguePlayer > 0) {
isPlayer = true;
}
return isPlayer;
}
Simply, this method will accept a player and a league and return whether or not this league has this player.
So I am writing test to test this behaviour... I realise that this test is a bit useless since I don't use user or league, but I have powered it down to at least get it to run with a simple count.
[TestFixture]
public class GameWorldTests
{
[Test]
public void logged_in_user_is_a_gameworld_player()
{
GameworldPlayerOperations gwp = new GameworldPlayerOperations();
Assert.IsFalse(gwp.isMemberOf("ewijfeiw", 1));
}
}
My test is failing... which isn't what I expected. So on debugging my test I found that the method was crashing my application with the following message:
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: An error occurred while executing the command definition. See the inner exception for details.
I have never seen a message like this before. Can anyone tell me what I'm doing wrong, please?
Thanks.
Related
I have my method as below which adds new user to database when such user name doesn't exist in database. If user name exist it throws custom exception therefore addUserType method is not reached.
public void CreateUserType(UserType userType)
{
if (userType == null) throw new ApplicationException("UserType object cannot be null");
if (_bottleClientQuery.IsUserTypeExist(userType.Name)) throw new ApplicationException("Such user type name already exist");
_bottleClientRepository.AddUserType(userType);
}
My testing methods are as shown below:
This method correctly giving me the expected result:
[Test]
public void CreateUserType_UserTypeExists_ThrowsApplicationException()
{
UserQuery.Setup(uow => uow.IsUserTypeExist(It.IsAny<string>())).Returns(true);
Assert.Throws<Exceptions.ApplicationException>(() => CreateClientService.CreateUserType(new UserType()));
}
Nevertheless in this method i want to check whether AddUserType was reached or not. I setup it as IsUserTypeExist returns true which means such user name exist therefore
AddUserType will be not reached.
[Test]
public void CreateUserType_UserTypeExists_AddUserTypeRepositoryNotReached()
{
UserQuery.Setup(uow => uow.IsUserTypeExist(It.IsAny<string>())).Returns(true);
CreateClientService.CreateUserType(new UserType());
UserRepository.Verify(uow => uow.AddUserType(It.IsAny<UserType>()),Times.Never);
}
The problem with second test method is the ApplicationException is thrown (that's fully fine and expected) but i would really like to test whether AddUserType was not reached.
Is it possible when before thrown exception was there?
You could change your test method to something like this;
[Test]
public void CreateUserType_UserTypeExists_AddUserTypeRepositoryNotReached()
{
UserQuery.Setup(uow => uow.IsUserTypeExist(It.IsAny<string>())).Returns(true);
Assert.Throws<ApplicationException>(() => CreateClientService.CreateUserType(new UserType()));
UserRepository.Verify(uow => uow.AddUserType(It.IsAny<UserType>()),Times.Never);
}
This will both verify that the expected exception is thrown and ensure that execution continues to your next verification.
I have a C#/.Net/WPF/MVVM application.
The application runs fine when running through VS 2015.
When I run the application standalone (on a different machine),
I get the following exception at startup:
An unhandled exception of type "System.InvalidOperationException"
occurred in WindowsBase.dll
Additional information "{DependencyProperty.UnserValue} is not a valid
value for property "TopLevelItemTemplateKey"
What is really going on?
How do I debug this?
Thanks
Are you returning directly your value on the get of your Dependency? The good manner would be to test if the variable is null before returning it here an example with an ObservableCollection:
public ObservableCollection<YourObject> _ocYourObject;
public ObservableCollection<YourObject> ocYourObject{
get {
if (_ocYourObject == null) {
_ocYourObject = new ObservableCollection<YourObject>();
}
return _ocYourObject;
}
set {
if (_ocYourObject!= value) {
_ocYourObject= value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(ocYourObject)));
}
}
}
I'm trying to learn automation with Selenium Webdriver using c#. I have my custom method Assert. What I did to continue the test after catching an AssertFailedException is using try-catch below is my code
public static void assert(string value, IWebElement element)
{
try
{
Assert.AreEqual(value, element.Text);
}
catch (AssertFailedException e)
{
Console.WriteLine(e.Message.ToString());
}
}
My problem is it catches all AssertFailedException(which is my goal) but the result of the test is PASSED in visual studio. My question is, how do I implement Continue on Failure and Fail the test if the Console contains Exceptions. Thankyou in advance guys!
As far as I understand, you want to do several checks inside your test, and at the very end of it to determine whether any of of them failed. You may need to write some custom code to achieve this. For example, you may introduce a class Assertion:
internal class Assertion
{
private readonly string title;
private readonly object expected;
private readonly object actual;
public Assertion(string title, object expected, object actual)
{
this.title = title;
this.expected = expected;
this.actual = actual;
}
public bool IsMatch()
{
return this.actual == this.expected;
}
public override string ToString()
{
return $"Title: {title}. Expected: {expected}. Actual: {actual}";
}
}
When your test is running, you will create new instances of Assertion class and store them in a list. At the end of the test, you can use the following method:
private static void VerifyAssertions(Assertion[] assertions)
{
var failedAssertions = assertions.Where(a => !a.IsMatch()).ToArray();
if (failedAssertions.Any())
{
throw new AssertFailedException(string.Join<Assertion>("; ", failedAssertions));
}
}
You could try using verify instead of assert for minor checks. Assert by default indicates a major checkpoint and script execution will be terminated on fail and if you catch that exception the reporting will be ignored - this is expected behaviour. However, a verify indicates that the script can continue even on fail - in this case the failed step will be reported and the script will continue.
To put it simply, use assert when you don't want the script to proceed on failure and use verify when you want the script to report the failure and proceed.
I am importing unity3D project for windows phone 8. and adding few lines of code which interact the c# code to the event changing handler of Object(SphereScript) in unity3D.
var sphereScript = UnityEngine.Object.FindObjectOfType<SphereScript>();
sphereScript.SphereStateChanged += sphereScript_SphereStateChanged;
sphereScript_SphereStateChanged(sphereScript.IsSphereMoving);
The project compiled fine with no errors but when it runs on phone it gives an error on line
UnityEngine.Object.FindObjectOfType<SphereScript>();
An exception of type 'System.Runtime.InteropServices.SEHException' occurred in UnityEngine.DLL but was not handled in user code. i don't know why this error occurs. but first time when i started the project it asked me to locate the file name UnityEngineObject.cs. Where can i find this file or how can i solve the problem. Thanks.
Url for complete code http://docs.unity3d.com/Manual/wp8-unity-interaction.html
Exception details:
System.Runtime.InteropServices.SEHException was unhandled by user code
HResult=-2147467259
Message=External component has thrown an exception.
Source=UnityEngine
ErrorCode=-2147467259
StackTrace:
at UnityEngine.Internal.$Calli.Invoke38(Int32 arg0, IntPtr method)
at UnityEngine.Object.FindObjectsOfType(Type type)
at UnityEngine.Object.FindObjectOfType(Type type)
at UnityEngine.Object.FindObjectOfType[T]()
at UnityXamlInteractionExample.MainPage.Unity_Loaded()
InnerException:
in Unity 5x i had equal the problem.
So try this:
In script SphereScript.cs:
re-write this:
public event Action<bool> SphereStateChanged;
to this:
public static event Action<bool> SphereStateChanged = delegate { };
next, in Visual Studio after build project un-comment these parts of code:
UnityApp.SetLoadedCallback(() => { Dispatcher.BeginInvoke(Unity_Loaded); });
private void Unity_Loaded() { }
now insert into private void Unity_Loaded() this:
ShareScript.SphereStateChanged += SphereStateChanged;
and finally add this:
void SphereStateChanged(bool currentSpehreState)
{
Dispatcher.BeginInvoke(() =>
{
SphereStateTextBlock.Text = currentSpehreState ? "Spehre is moving" : "Sphere is stopped";
});
}
Good luck, bye :)
I've just started playing around with Moq in my unit tests, but am having an issue where the unit test is passing - and I don't think it should be.
I have two objects, one that despatches data to a queue and another that implements INotifier which is called if the despatcher fails, they look like this (cut down for brevity):
public class EmailNotifier : INotifier
{
public void Notify(string message)
{
// sends the notification by email
}
}
public class Despatcher
{
public void Despatch(int batchNumber, INotifier failureNotifier)
{
try
{
if (batchNumber.Equals(0)) throw new InvalidOperationException("Error message");
}
catch (InvalidOperationException ex)
{
failureNotifier.Notify(ex.ToString());
throw ex;
}
}
}
I am unit testing the Despatcher to specifically verify that Notify is being called on the provided INotifier (which I'm mocking) when it fails (I'm intentionally forcing the Despatcher to fail by passing a 0 batch number). I set up my mocks like this:
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void Despatcher_notifies_on_failure()
{
var mockNotifier = new Mock<EmailNotifier>();
mockNotifier.Setup(n => n.Notify(It.IsAny<string>())).Verifiable();
var despatcher = new Despatcher();
despatcher.Despatch(0, mockNotifier.Object);
mockNotifier.Verify(n => n.Notify(It.IsAny<string>()), Times.Once());
}
This passes the test fine, which is expected as a 0 batch number raises the exception which causes the INotifier to call Notify (when I step through the test everything works as expected).
So, I go on to comment out the failureNotifier.Notify(ex.ToString()) line and run the test again - passes fine? I'm not sure whether I'm setting up and verifying correctly as I've only been using Moq for about 2 hours now but I thought I was understanding this correctly, but this has just thrown me a bit. I expect this test to fail as I specifically want to make sure Notify is called in the event of a failure - can anyone see anything obviously wrong here? Thanks in advance for your help as always.
Your test never gets to the verification part. Why? This line
despatcher.Despatch(0, mockNotifier.Object);
Throws exception, which is consumed by ExpectedException attribute and test ends. The mockNotifier.Verify line is never executed.
What you want is two unit tests, instead:
one testing that notifier is called upon exception (with .Verify). Note that you'll have to wrap .Despatch call into try { } catch { }, so that exception is ignored.
second, checking that exception is rethrown (with ExpectedException)