Tutorial – BDD and Dependency Injection in .Net (4) [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Please help me in removing Mock error in bold letters.
Error 1 The type or namespace name 'Mock' could not be found (are you
missing a using directive or an assembly
reference?) C:\Users\MOB140003208\documents\visual studio
2012\Projects\RockPaperScissors\RockPaperScissorsTest\Tests\GameTest.cs 65 34 RockPaperScissorsTest
Error 2 The type or namespace name 'Mock' could not be found (are you
missing a using directive or an assembly
reference?) C:\Users\MOB140003208\documents\visual studio
2012\Projects\RockPaperScissors\RockPaperScissorsTest\Tests\GameTest.cs 77 34 RockPaperScissorsTest
Error 3 The type or namespace name 'Mock' could not be found (are you
missing a using directive or an assembly
reference?) C:\Users\MOB140003208\documents\visual studio
2012\Projects\RockPaperScissors\RockPaperScissorsTest\Tests\GameTest.cs 89 34 RockPaperScissorsTest
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RockPaperScissors;
namespace RockPaperScissorsTest.Tests
{
/// <summary>
/// Summary description for GameTest
/// </summary>
[TestClass]
public class GameTest
{
public GameTest()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void ReturnsCorrectMessageIfPlayerWins()
{
var engineMock = new **Mock**();
engineMock.Setup(de => de.Result(Move.Rock, Move.Paper)).Returns(GameResult.PlayerWins);
var game = new Game(engineMock.Object);
game.PlayerMove = "Paper";
var result = game.Result();
engineMock.VerifyAll();
Assert.AreEqual("Player Wins!", result);
}
[TestMethod]
public void ReturnsCorrectMessageIfComputerWins()
{
var engineMock = new **Mock**();
engineMock.Setup(de => de.Result(Move.Rock, Move.Scissors)).Returns(GameResult.ComputerWins);
var game = new Game(engineMock.Object);
game.PlayerMove = "Scissors";
var result = game.Result();
engineMock.VerifyAll();
Assert.AreEqual("Computer Wins!", result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ThrowsErrorIfPlayerMoveIsNotSet()
{
var engineMock = new **Mock**();
var game = new Game(engineMock.Object);
game.Result();
}
}
}

are you missing a using directive or an assembly reference?
Yes you are. You need to add a reference to the assembly containing the Mock type. You also need to add a using statement to be able to use the Mock type without having to add the namespace in front.
So make sure that you have a reference to the Moq assembly (preferably by using NuGet) and make sure that you add using Moq; at the top of your source code.

Related

Referencing of classes and namespaces Visual Studio 2017

I noticed for my little project that when importing classes some use full folder reference while otheres don't.
Here is code from project Mini that i am working on.
Models folder
Contains two entities, Auto and Airplane
namespace Mini.Models {
public class Auto {
// code and stuff
}
}
namespace Mini.Models {
public class Airplane {
// code and stuff
}
}
Services folder Contains single service class
namespace Mini.Services
{
public class AutoService : IAutoService {
public bool Get() {
var autoObject = new Models.Auto(); // notice how it references Models folder
var planeObject = new Airplane(); // Same folder but not referencing Models in front of it
// other code
}
}
public interface IAutoService {
bool Get();
// others
}
}
While not a major bugbear, it is still annoying that two classes in same folder get referenced differently, and i cannot figure out why.
Any advice would be appreciated.
Error Message when removing Models folder
Error CS0118: 'Auto' is a namespace but is used like a type (34, 27)
Based on the error message you have provided:
Error CS0118: 'Auto' is a namespace but is used like a type (34, 27)
It would appear that you have a namespace called Auto. Imagine the following example:
namespace MyApp.Auto
{
class Test
{
}
}
namespace MyApp
{
class Auto
{
}
class MyTest
{
private Auto test;
}
}
Because you can see, from the MyApp namespace, both a class called Auto and a namespace called Auto (either namespace MyApp.Auto or simply namespace Auto), C# isn't sure which one you want. As such, it's forcing you to be specific in choosing one or the other.
The easiest solution is to change the MyApp.Auto namespace to something else.
This is not fix but explaining with proper code sample (and why ).
namespace Mini.Models
{
public class Auto
{
// code and stuff
}
}
namespace Mini.Models
{
public class Airplane
{
// code and stuff
}
}
namespace Mini.Auto
{
public class OtherAirplane
{
// code and stuff
}
}
namespace Mini
{
using Mini.Models;
using namespaceAuto = Auto ; /// this also not fix the issue.
class NamespaceIssue
{
void execute()
{
var autoObject = new Auto(); // Error
var planeObject = new Airplane(); // Same folder but not referencing Models in front of it
// other code
}
}
}
now you can see some were in code you have "Mini.Auto" namespace , and it is couching issue.
i tested for VS 2015 have same issue. maybe we have to report to VS team or it is by design .
The issue seemed to be with VS2017 or the way it created the project first time around.
Upon starting brand new project (ASP Core 2.2, Web API, with https enabled and docker disabled), and using same classes the issue was non-existant.

Why am I facing "The type or namespace name 'UnitTestClassBase' could not be found (are you missing a using directive or an assembly reference?)"?

I am using Testleft to automate test scenarios.
Using VS for the 1st time.
This is the code:
############################################################################
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Text;
using SmartBear.TestLeft;
using SmartBear.TestLeft.TestObjects;
using SmartBear.TestLeft.TestObjects.Win;
using System.IO;
namespace TestLeftProject1
{
[TestClass]
public class TestLeftTest : UnitTestClassBase
{
#region Class initializers
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
UnitTestClassBase.InitializeClass(context);
}
[ClassCleanup]
public static void ClassCleanUp()
{
UnitTestClassBase.FinalizeClass();
}
#endregion
[TestMethod]
public void TestMethod1()
{
// Runs the Notepad application
IProcess process = Driver.Applications.Run("notepad.exe");
// Gets Notepad's edit box
IWinTextEdit edit = process.Find<ITopLevelWindow>(new WindowPattern()
{
WndClass = "Notepad"
}).Find<IWinTextEdit>(new WindowPattern()
{
WndClass = "Edit"
});
// Simulates a mouse click in Notepad
edit.Click();
// Simulates text input in Notepad
string inputText = "test";
edit.SetText(inputText);
// Verifies the text that Notepad contains
Assert.AreEqual(inputText, edit.wText);
// Posts messages to the TestLeft test log
Driver.Log.Screenshot(edit, "Notepad's edit box screenshot");
Driver.Log.Warning("A warning message");
// Saves the TestLeft test log
string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), DateTime.Now.ToString("MM_dd_yyyy_H_mm_ss"));
Driver.Log.Save(logPath, Log.Format.Html);
}
}
}
I have tried other solutions like changing the target framework from 4.5 to 4 and 4.5.1.
I am not sure what to do. I am new to VS. Please help
you need to add a class with the name UnitTestClassBase.
Anyway have a look how to write good unit tests. You should also use the pattern Arrange, Act and Assert
You are most likely missing a reference to the assembly SmartBear. To validate this, go to the references in the solution explorer and check this assembly is referenced. If it isn't, add it as a reference.

Visual Studio 2015 intellisense and ambiguous namespaces

The Xamarin.Auth project broke up i.e. the source code was compiling OK and after another Xamarin.Android update it was suddenly broken.
It turned out that the problem arose after the Mono.Android.dll (Xamarin.Android) was extended by several namespace definitions.
I hunted the problem down to the following:
There is a dll #1 (Mono.Android.dll):
namespace Xamarin.Android
{
public class Class1
{
}
}
namespace Android.OS
{
public class Class2
{
}
}
There is a dll #2 (Xamarin.Auth.Android.dll):
namespace Xamarin.Auth
{
//This does not compile. See the problem description below.
public class User1 : Android.OS.Class2
{
}
}
Intellisense shows the following problem:
Error CS0234 The type or namespace name 'OS' does not exist in the namespace 'Xamarin.Android' (are you missing an assembly reference?)
This can be fixed by changing the latter namespace to something else or by using the global:: identifier:
namespace SomeOtherNamespace
{
//This compiles ok.
public class User1 : Android.OS.Class2
{
}
}
namespace Xamarin.Auth
{
//This compiles ok.
public class User1 : global::Android.OS.Class2
{
}
}
The question is: why does not intellisense give a warning that the Android namespace branch is ambiguous between global::Xamarin.Android and global::Android? What is the good way out of it? Always use global:: namespace identifier?
You can use the global directive to tell the compiler it should evaluate the namespace from the root, else it tries to evaluate the namespace relative from the current namespace. Using global always uses the full qualified namespace name, so that is why it works when you prefix it.
Another option would be using an alias:
using AOS = Android.OS;
namespace Xamarin
{
public class User1 : AOS.Class2
{
}
}

TestContext is null when running test from a Windows Form

I have an issue related to running CodedUITests from a Windows Form. (it works in the CodedUITestProject with Test-Explorer).
This is my CodedUITest's structure :
[CodedUITest]
public class DBTest
{
#region Static Fields
public static CSVReader csvReader;
#endregion
#region Fields
public string logFileName;
public string timer = String.Empty;
public TestRead testRead;
public UploadResults uploadResults;
private DateTime testStart;
#endregion
[ClassInitialize]
public static void MyTestInitialize(TestContext test)
{
csvReader = new CSVReader();
csvReader.LoadTestValues("steam.csv");
}
[TestInitialize]
public void testInit()
{
testStart = DateTime.Now;
}
[TestMethod(), TestCategory("Reflection"), TestCategory("DataDriven"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", #"|DataDirectory|\CSV's\steam.csv", "steam#csv", DataAccessMethod.Sequential), DeploymentItem(#"..\..\CSV's\steam.csv")]
public void steamAccess()
{
testRead = new TestRead();
SteamMap a = new SteamMap();
testRead.Read(a, TestContext);
}
[TestCleanup]
public void TestCleanup()
{
uploadResults = new UploadResults();
//timer for each test ( in seconds )
double diffSecs = (DateTime.Now - testStart).TotalSeconds;
uploadResults.TestUpload(testRead.TestResults, csvReader.DataTable, diffSecs,TestContext);
}
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
private TestContext testContextInstance;
}
This runs perfectly from VS's Test Explorer, testContextInitialize variable gets initialized.
In the same Solution I've added a second project, a simple Windows Form application, added a reference to my DLL ( from References) which runs the following code :
Playback.Initialize();
DBTest a = new DBTest();
a.steamAccess();
Playback.Cleanup();
NullReferenceException occurs, my testContex is null when I run my test from outside it's assembly.
I need some help in this matter, Thanks
Edit 1:
Test Class :
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Input;
using System.Windows.Forms;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using System.Linq;
using System.Reflection;
using SimarpiDB.GLobal;
using SimarpiDB.UITestMaps.SteamMapClasses;
using SimarpiDB.Global;
using System.Data;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("TestLauncher")]
namespace SimarpiDB
{
[CodedUITest]
public class.....
Edit 2:
Temporary workaround until I find the cause of this error :
From my Windows Form I launch a MSTest with few required parameters and most of the what-methods-to-run logic will come from my database. I already did this few months ago but I scraped it because it's an additional performance overhead to use a tool such as MsTest within a launcher such as mine.
For anyone interested, there's a file located within VS's installation directory, it's called VsDevCmd.bat, I load this .bat within a hidden-in-background cmd with few additional commands ( mstest, testcontainer, test). This works but as I said I have no other plausible ideas.
There may also be a lack of referenced libraries within my Form ? Maybe something, a .dll that initialized the testenvironment and the testContext variable.
I wrote this because there may be others seeking the same result.
To clarify on my comment: internal is default in C#, so declaring something as abstract is like declaring it as "internal abstract".
For InternalsVisibleTo, you must make the library project visible to the test project, not the other way around:
[assembly:InternalsVisibleTo("MyTestProject")]

How to compile C# application through Command Prompt

I have one folder. In that I have three cs files.
Demo.cs
using System;
namespace Demo
{
public class Test
{
public static Entity entity = new Entity();
public static void Main(string[] args)
{
var objectHandler = Activator.CreateInstance(null,
args);
var obj = objectHandler.Unwrap();
entity.GetAnnotation(obj.GetType());
}
}
}
Entity.cs
using System;
namespace Demo
{
public class Entity
{
public void GetAnnotation(Type classname)
{
Attribute[] dataAnnotationlist = Attribute.GetCustomAttributes(propInfo);
foreach (var dataannotationAttribute in dataAnnotationlist)
{
//some operation to get annotation property from Employee.cs class
}
}
}
}
Employee.cs
using System.ComponentModel.DataAnnotations;
namespace Demo
{
public class Employee
{
[Display(Name = "name")]
public string name { get; set; }
}
}
I have created XML file format from class file (Employee.cs) using reflection.
But error occurred when try to run through Command Prompt. It runs in visual studio.
I want to run Test.cs, Entity.cs using command prompt with passing "Employee.cs" as a string parameter to Main method.
Now, I have passed hard coded as,
System.Runtime.Remoting.ObjectHandle objectHandler = Activator.CreateInstance(null, "Demo.Employee");
Its working fine but how to pass it through command.
Error Occurred is:
Entity.cs(8,29): error CS0234: The type or namespace name
'DataAnnotations' does not exist in the namespace
'System.ComponentModel' (are you missing an assembly reference?) Entity.cs(9,19): error CS0234: The type or namespace name
'Objects'
does not exist in the namespace 'System.Data' (are you missing an
assembly reference?) Employee.cs(6,33): error CS0234: The type or namespace name 'DataAnnotations' does
not exist in the namespace 'System.ComponentModel' (are you missing an
assembly reference?)
and it also shows error for "DataAnnotations" and "Objects".
how can i solve this problem?
One option to simply build .csproj with MSBUILD.
More entertaining is to configure all dependencies yourself via command line arguments of csc. For your immediate error you need to add references with /r: command similar to following
csc /out:Test.exe /r:System.ComponentModel.DataAnnotations.dll *.cs
For more details on command line arguments of csc check help csc /? or on MSDN CSC command line options and Building with CSC.

Categories

Resources