Specflow with NUnit don't respect TestFixtureSetUpAttribute - nunit

I'm using SpecFlow with Nunit and I'm trying to setup my enviroment tests using TestFixtureSetUpAttribute, but it's never called.
I already tried to use MSTests and ClassInitialize attribute, but the same happen. The function isn't called.
Any ideas Why?
[Binding]
public class UsersCRUDSteps
{
[NUnit.Framework.TestFixtureSetUpAttribute()]
public virtual void TestInitialize()
{
// THIS FUNCTION IS NEVER CALLER
ObjectFactory.Initialize(x =>
{
x.For<IDateTimeService>().Use<DateTimeService>();
});
throw new Exception("BBB");
}
private string username, password;
[Given(#"I have entered username ""(.*)"" and password ""(.*)""")]
public void GivenIHaveEnteredUsernameAndPassword(string username, string password)
{
this.username = username;
this.password = password;
}
[When(#"I press register")]
public void WhenIPressRegister()
{
}
[Then(#"the result should be default account created")]
public void ThenTheResultShouldBeDefaultAccountCreated()
{
}
Solution:
[Binding]
public class UsersCRUDSteps
{
[BeforeFeature]
public static void TestInitialize()
{
// THIS FUNCTION IS NEVER CALLER
ObjectFactory.Initialize(x =>
{
x.For<IDateTimeService>().Use<DateTimeService>();
});
throw new Exception("BBB");
}
private string username, password;
[Given(#"I have entered username ""(.*)"" and password ""(.*)""")]
public void GivenIHaveEnteredUsernameAndPassword(string username, string password)
{
this.username = username;
this.password = password;
}
[When(#"I press register")]
public void WhenIPressRegister()
{
}
[Then(#"the result should be default account created")]
public void ThenTheResultShouldBeDefaultAccountCreated()
{
}

Your TestInitialize is not called because it is inside your Steps class and not inside in an Unit Tests (because the actual unit test is inside the .cs which is generated from your .feature file).
SpecFlow has it's own test-lifetime events which are called hooks, these are all the predefined hooks:
[BeforeTestRun] / [AfterTestRun]
[BeforeFeature] / [AfterFeature]
[BeforeScenario] / [AfterScenario]
[BeforeScenarioBlock] / [AfterScenarioBlock]
[BeforeStep] / [AfterStep]
Note that this allows for greater flexibility in setup. For additional information see the documentation.
Based on the fact that you want to use the TestFixtureSetUp attribute you will probably need the BeforeFeature hook which will be called once before each feature, so you need to write:
[Binding]
public class UsersCRUDSteps
{
[BeforeFeature]
public static void TestInitialize()
{
ObjectFactory.Initialize(x =>
{
x.For<IDateTimeService>().Use<DateTimeService>();
});
throw new Exception("BBB");
}
//...
}
Note that the [BeforeFeature] attribute needs a static method.
You should also note that if you are using the VS integration there is an project item type called SpecFlow Hooks (event bindings) which creates a binding class with some predefined hooks to help you get started.

Related

Roslyn codefix and fixall action not executed properly under unit test

I've 'successfully' written a CodeFix and FixAllProvider, BUT...
The diagnostic I'm trying to handle can occur multiple times in the same document on the same line. However, the behavior under unit test (CSharpCodeFixTest) stumps me.
If a test generates only one instance of the diagnostic, CSharpCodeFix<> calls the CodeFix initially then calls the FixAllProvider multiple times during Verification. The test succeeds.
If a test generates more than one diagnostic, CSharpCodeFix<> calls the CodeFix once. CSharpCodeFix<> never calls the FixAllProvider, and since the CodeFix cannot fix all instances. the test fails the before/after document comparison.
Note that in these samples, namespaces (not shown) disambiguate the classes from their bases. I've removed the fix implementations because I believe them irrelevant to the problem.
First the CodeFix
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CodeFixProvider)), Shared]
public class CodeFixProvider : Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(EGNT0003NoInlineInstantiationAnalyzer.DiagnosticId); }
}
public sealed override Microsoft.CodeAnalysis.CodeFixes.FixAllProvider GetFixAllProvider()
{
Microsoft.CodeAnalysis.CodeFixes.FixAllProvider provider = FixAllProvider.Instance;
return provider;
}
public static readonly string EquivalenceKey = "EG0003CodeFixProvider";
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (Diagnostic diagnostic in context.Diagnostics.Where(d => FixableDiagnosticIds.Contains(d.Id)))
{
context.RegisterCodeFix(CodeAction.Create(title: "Introduce local variable",
token => GetTransformedDocumentAsync(context.Document, diagnostic, token),
equivalenceKey: EquivalenceKey), diagnostic);
}
return Task.CompletedTask;
}
;
Here is the FixAllProvider
public sealed class FixAllProvider : Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
{
private FixAllProvider()
{
}
private static readonly Lazy<FixAllProvider> lazy = new Lazy<FixAllProvider>(() => new FixAllProvider());
public static FixAllProvider Instance
{
get
{
return lazy.Value;
}
}
public override IEnumerable<string> GetSupportedFixAllDiagnosticIds(Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider originalCodeFixProvider)
{
string[] diagnosticIds = new[]
{
EGNT0003NoInlineInstantiationAnalyzer.DiagnosticId,
};
return diagnosticIds;
}
public override async Task<CodeAction> GetFixAsync(FixAllContext fixAllContext)
{
:
Finally here is the CodeAction invoked by the FixAllProvider.
public class FixAllCodeAction : CodeAction
{
private readonly List<KeyValuePair<Document, ImmutableArray<Diagnostic>>> _diagnosticsToFix;
private readonly Solution _solution;
public FixAllCodeAction(string title, Solution solution, List<KeyValuePair<Document, ImmutableArray<Diagnostic>>> diagnosticsToFix)
{
this.Title = title;
_solution = solution;
_diagnosticsToFix = diagnosticsToFix;
}
public override string Title { get; }
public override string EquivalenceKey => "EG0003CodeFixProvider";
protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
{
Solution newSolution = _solution;
:
I've debugged through CSharpCodeFixTest<> and continue to do so. I'm hoping someone has seen this issue before and can see my mistake.
I expected to see the code fix tests to complete successfully. I verified through other means that the documents produced by the CodeFix and the FixAllProvider are valid and correct.

NInject simplest example doesn't work

I've got three projects:
UI
PluginManager
PluginOne
PluginTwo
Inside my Plugin Manager a create a simple plugin interface:
public interface IPlugin<T>
{
void sayMessage(T message);
T createMessage();
}
So, in my other projects I've two IPlugin implementation:
In porject PluginOneProject -->
-------------------------------
public class PluginOne : IPlugin<IntMessage>
{
public void sayMessage(IntMessage message)
{
System.Console.WriteLine(message.ToString());
}
}
where:
public class IntMessage
{
private int message;
public IntMessage(int message)
{
this.message = message;
}
public override string ToString()
{
return this.message.ToString();
}
}
In porject PluginTwoProject -->
-------------------------------
public class PluginTwo : IPlugin<StringMessage>
{
public void sayMessage(StringMessage message)
{
System.Console.WriteLine(message.ToString());
}
}
where:
public class StringMessage
{
private String message;
public StringMessage(String message)
{
this.message = message;
}
public override string ToString()
{
return this.message.ToString();
}
}
Obviously, I've added the corresponding project references.
So, in my UI porject I've NInject, and I perform this convention mapping:
kernel.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(IPlugin<>))
.BindAllInterfaces()
);
The graph is built correctly.
So, I don't know how to get an instance of PluginOne, or PluginTwo from UI project.
I'm trying to use this code, however, I've a problem with generic interfaces...
foreach (IPlugin<?> plugin in kernel.GetAll(typeof(IPlugin<>)))
{
plugin.sayMessage(plugin.createMessage());
}
Unfortunately, you must request a specific interface from Ninject, so you must request either IPlugin<IntMessage> or IPlugin<StringMessage>.
I would suggest trying to refactor your app so that you can request a more generic interface, such as IPlugin, and/or create a message interface like IMessage that each message implements. It's not clear from your question what you're trying to accomplish.

How to use set , get in gwt shared folder

I have a class select in gwt shared folder with some set and get function like..
public class Select implements Serializable {
private static final long serialVersionUID = 1L;
String userid=null;
String name=null;
/******************Set********************/
public void setId(String userid) {
this.userid=userid;
}
public void setName(String name) {
this.name=name;
}
/******************get*************************/
public String getId() {
return userid;
}
public String getName() {
return name;
}
now I called setid() and getid() from server,its working . but when i am calling getid() from client, its returning me a null value please some one help me ...
my client side code is ...
greetingService.select(new AsyncCallback<String>()
{
Select sel=new Select();
public void onSuccess(String result) {
System.out.println("client..id"+sel.getId());
});
sel.getid() is returning null because its not being set by anything. You are simply calling new Select() and creating a new Select object on the client. If you want to retrieve the Select object with data in it form the server you need to pass it as the result parameter of the AsyncCallback callback via an RPC service, like so:
greetingService.select(new AsyncCallback<Select>() {
public void onSuccess(Select result) {
// Do what you want with the Select object returned via server
}
public void onFailure(Throwable caught) {
System.out.println("Call failed " + caught.getMessage());
}
});
Assuming you have set up the RPC service properly, you will handle the server end as a regular method:
public class GreetingServiceImpl extends RemoteServiceServletImpl {
public Select select() {
Select select = new Select();
select.setId(1);
return select;
}
}
You may find this tutorial helpful http://www.gwtproject.org/doc/latest/tutorial/RPC.html

POJO information lost during RPC call (GWT)

I am having issues with RPC calls and GWT. Essentially, I have a Person class (common code between client and server) that is created in the client side web code, sent to the server code via an RPC call, and then saved to a DB (OrientDB). I have verified that the following work:
RPC call - I am able to send info to the server and retrieve info from the server
save to DB - have verified that a Person object is saved to the DB
Where I am having issues is the transfer of the POJO from the client to the server. I have verified that the POJO's properties are intact right before it is sent to the server, however, the object passed to the server contains null values for all properties. Essentially, the class is transferred but the information is not. It then saves to the DB, but obviously without any relevant information contained within it.
I will copy what I feel is relevant below, please let me know what else I can provide to make this problem easier to identify. Note these are still in a testing state, so mind the comments :)
Any idea why my POJO's information is being lost in translation?
Person object, followed by the abstract class it inherits from:
public class Person extends org.matesweb.shared.AbsPerson implements Serializable
{
#Id
private String id; // DON'T CREATE GETTER/SETTER FOR IT TO PREVENT THE CHANGING BY THE USER APPLICATION,
// UNLESS IT'S NEEDED
//sets new user details
public void setPerson(String fIrstName, String mIdInit, String lAstName, String email, String password)
{
firstName = fIrstName;
middleInitial = mIdInit;
lastName = lAstName;
}
/*getter and setter methods - required for every
* field due to restrictions imposed by OrientDB*/
public Object getId()
{
String tmp;
tmp = id.toString();
return tmp;
}
//end class
}
public class AbsPerson implements Serializable
{
String firstName;
String middleInitial;
String lastName;
// public sys.Login login;
public org.matesweb.shared.Group[] groups;
private org.matesweb.shared.Purchase[] purchases;
/*this method adds a new purchase to the purchases variable*/
/* public void addPurchase(float price, String description)
{
people.Purchase newPurchase = new people.Purchase(login, price, description);
}
*/
/*adds a person to a group by comparing the passed in group ID and PWD*/
public void addGroup(String groupID, String groupPWD)
{
//compare group ID with group PWD to add a user to the group
}
/*getter and setter methods - required for every
* field due to restrictions imposed by OrientDB*/
public String getFirstName()
{
return firstName;
}
public void setFirstName(String name)
{
firstName = name;
}
public String getMiddleInitial()
{
return middleInitial;
}
public void setMiddleInitial(String midInit)
{
middleInitial = midInit;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String ln)
{
lastName = ln;
}
/*
public sys.Login getLogin()
{
return login;
}
public void setLogin(sys.Login log)
{
login = log;
}
*/
public org.matesweb.shared.Group[] getGroups()
{
return groups;
}
public void setGroups(org.matesweb.shared.Group[] gro)
{
groups = gro;
}
public org.matesweb.shared.Purchase[] getPurchases()
{
return purchases;
}
public void setPurchases(org.matesweb.shared.Purchase[] purch)
{
purchases = purch;
}
}
Service
package org.matesweb.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import org.matesweb.shared.Person;
#RemoteServiceRelativePath("peopleService")
public interface PeopleService extends RemoteService {
//test services
String stringTest(String outgoingString);
Person getPerson(String persId);
//production services
String savePerson(Person p);
}
ServiceAsync
import com.google.gwt.user.client.rpc.AsyncCallback;
import org.matesweb.shared.Person;
public interface PeopleServiceAsync
{
//tests
void stringTest(String outgoingString, AsyncCallback<String> incomingString);
void getPerson(String persId, AsyncCallback<Person> retPerson);
//production services
void savePerson(Person p , AsyncCallback<String> st);
}
ServiceImpl call for this particular method:
//production calls
#Override
public String savePerson(Person p) {
String st = ioObj.saveObj(p);
if(st.equals("Success")){
return "Your information has been saved successfully!";
} else{
return "Something has gone wrong on our end... Sorry! Error:<br /> " + st;
}
}
and finally, the call itself
private static void savePerson(Person p)
{
// Initialize the service proxy.
if (peopleSvc == null) {
peopleSvc = GWT.create(PeopleService.class);
}
//resets status
st="";
// Set up the callback object.
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable caught) {
st = caught.getMessage();
Label stLabel= new Label(st);
personTable.setWidget(3,1,stLabel);
}
#Override
public void onSuccess(String result) {
st = result;
HTML stLabel= new HTML(st);
joinPanel.add(stLabel);
}
};
// Make the call to the people service.
peopleSvc.savePerson(p, callback);
}
I was able to fix this issue by implementing GWT's IsSerializable interface. I also removed the Serializable interface from the Person class and let it inherit IsSerializable from the abstract class it inherits from.

GWT - Manage a boolean method in the RPC configuration

I have make my own method in the RPC schema by using the GWT framework. Now, i need to add another method.
So, i wrote this code for each part of RPC :
package org.sinfonet.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("gwtservice")
public interface GWTService extends RemoteService {
public String checkLogin(String nickname, String password);
public boolean anotherFunction(String nickname);
}
#########################################################
package org.sinfonet.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GWTServiceAsync {
public void checkLogin(String nickname, String password, AsyncCallback<String> callback);
public void anotherFunction(String nickname, AsyncCallback<java.lang.Boolean> asyncCallback);
}
#########################################################
package org.sinfonet.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.ArrayList;
import org.sinfonet.client.GWTService;
import org.sinfonet.mgmt.Configuration;
import org.sinfonet.mgmt.Database;
public class GWTServiceImpl extends RemoteServiceServlet implements GWTService {
public String checkLogin(String nickname, String password) {
Database mydb=Configuration.getDatabase();
mydb.connetti();
// faccio md5 ed escape
String log_check_user=nickname;
String log_check_pass=password;
// controllo che l'utente esista
ArrayList<String[]> db_result=null;
db_result=mydb.selectQuery("SELECT nickname FROM users WHERE nickname='"+log_check_user+"' AND password='"+log_check_pass+"'");
if(db_result.size()!=0) {
return "YES";
}
// sconnessione al database
mydb.disconnetti();
return "NO";
}
public boolean anotherFunction(String nickname) {
// somethings others
return true;
}
}
#########################################################
final AsyncCallback<java.lang.Boolean> callCheckLogin = new AsyncCallback<java.lang.Boolean>() {
public void onSuccess(boolean result) {
if(result) {
designLogout(menu_login_label1.getText());
} else {
menu_err.setText("Username e password non validi");
}
}
};
// Listen for the button clicks
menu_login_button.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
// Make remote call. Control flow will continue immediately and later
// 'callback' will be invoked when the RPC completes.
getService().anotherFunction(menu_login_input1.getText(), callCheckLogin);
}
});
as you can see, i added the anotherFunction() method (boolean), but Netbeans says to me that i need to implements all abracts method about allCheckLogin, but i wont do it :) How can I fix this problem?
So Netbeans complains about the missing onFailure method, right? If you don't want to implement that method every time, write yourself an abstract class like:
public abstract class BaseAsyncCallback<T> implements AsyncCallback<T> {
#Override
public void onFailure(Throwable caught) {
// Perform generic failure handling
}
}
Then you can change your code into:
final AsyncCallback<java.lang.Boolean> callCheckLogin =
new BaseAsyncCallback<java.lang.Boolean>() {
public void onSuccess(java.lang.Boolean result) {
...
}
};
Now you don't need to implement onFailure anymore, except if you need to perform additional error handling.