Visual Studio 2010 Unit test allways gives NullReferenceException error - unit-testing

I am trying make Unit test with Unit test wizard, but I am always getting:
Test method TestProject9.Log_InsertMasterTest threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
My test.cs:
[TestMethod()]
[DeploymentItem("Engine.dll")]
public void Log_InsertMasterTest()
{
SkinnedRepairSearch_Accessor target = new SkinnedRepairSearch_Accessor(); // TODO: Initialize to an appropriate value
int RepairMasterID = 0; // TODO: Initialize to an appropriate value
int RepairMasterIDOld = 0; // TODO: Initialize to an appropriate value
int id = 0; // TODO: Initialize to an appropriate value
string Text = string.Empty; // TODO: Initialize to an appropriate value
target.Log_InsertMaster(RepairMasterID, RepairMasterIDOld, id, Text);
Assert.Inconclusive("A method that does not return a value cannot be verified.");
}
Log_InsertMaster method:
protected void Log_InsertMaster(int RepairMasterID, int RepairMasterIDOld, int id, string Text)
{
SqlConnection myConnection = new SqlConnection(Globals.DatabaseConnectionString);
SqlCommand myCommand = new SqlCommand("dbo.Repair_LogInsertMaster", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("#RepairMasterID", SqlDbType.Int).Value = RepairMasterID;
myCommand.Parameters.Add("#RepairMasterIDold", SqlDbType.Int).Value = RepairMasterIDOld;
myCommand.Parameters.Add("#DateTime", SqlDbType.DateTime).Value = System.DateTime.Now;
myCommand.Parameters.Add("#RepairID", SqlDbType.Int).Value = id;
myCommand.Parameters.Add("#UserSignature", SqlDbType.NVarChar, 200).Value = AdminUser.Signature;
myCommand.Parameters.Add("#Text", SqlDbType.NVarChar, 200).Value = Text;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
How to not get this error? And how to use Unint testing wizard?
Exception line:
SkinnedRepairSearch_Accessor target = new SkinnedRepairSearch_Accessor(); // TODO: Initialize to an appropriate value
I tried and other, public method:
[TestMethod()]
public void EmptyTextBoxesTest()
{
SkinnedRepair target = new SkinnedRepair(); // TODO: Initialize to an appropriate value
Control parent = null; // TODO: Initialize to an appropriate value
target.EmptyTextBoxes(parent);
Assert.Inconclusive("A method that does not return a value cannot be verified.");
}
same error

Related

Why does the object my C++ point to lose its values in my factory pattern?

I'm trying to use a factory pattern to create different types of "State" objects. The objects are returned with a pointer (State*) but shortly after the objects are created, the values they point to disappear (go to NULL or reset to boolean "true").
The code directly below is where it goes awry, but below that is a complete code sample that compiles and runs. Additionally, I've posted pictures of the debugger values before and after the usleep() command.
I feel like it may have something to do with scope and the garbage collector, but I'm not a C++ expert by any stretch of the imagination. I would have thought my pointer would have kept my referenced object alive.
// relevant code
void execute(){
// Calling the constructor directly as an example
State directState = State("temp", false, false, false);
// Using factory pattern to create a state. Just creating the "default" state as an example
State * factoryState = StateFactory::getDefaultState();
// factoryState -> name is "Reading" in the debugger, but when I try to print it out, it's gone
// Grab the names for easy reference
const char * dName = directState.name;
const char * fName = factoryState -> name;
usleep(1000000 / 100);
// factoryState -> name .... it's vanished?
usleep(1000000 / 100);
// TODO we would run the factoryState -> execute() function here
}
// Complete code example
#include <iostream>
#include <zconf.h>
// Main generic "State" class
class State {
public:
const char * name;
bool isReadable;
bool isExecuting;
bool isFinished;
State(const char name[], bool isReadable, bool isExecuting, bool isFinished){
this -> name = name;
this -> isReadable = isReadable;
this -> isExecuting = isExecuting;
this -> isFinished = isFinished;
}
};
// An inherited class. There will be lots of these eventually
class StateReading: public State { ;
public:
StateReading():State((const char *)"Reading", true, false, false) {}
};
// Factory method that will create lots of the different states
// note that it will be returning a pointer to a "State" object
class StateFactory {
public:
static State* getDefaultState(){
StateReading defaultState = StateReading();
State* state = &defaultState;
return state;
}
};
// Runs the various "States" in a template pattern
class StateExecutor {
public:
State * state;
StateExecutor(){
StateReading stateReading = StateReading();
state = &stateReading;
}
void execute(){
// Calling the constructor directly as an example
State directState = State("temp", false, false, false);
// Using factory pattern to create a state. Just creating the "default" state as an example
State * factoryState = StateFactory::getDefaultState();
// factoryState -> name is "Reading" in the debugger, but when I try to print it out, it's gone
// Grab the names for easy reference
const char * dName = directState.name;
const char * fName = factoryState -> name;
usleep(1000000 / 100);
// factoryState -> name .... it's disappeard?
usleep(1000000 / 100);
// TODO we would run the factoryState -> execute() function here
}
};
// The actual
void loop(StateExecutor stateExecutor) {
// Run the "execute" function of whatever the current state is
// The stateExecutor actually runs the state
stateExecutor.execute();
// Slow the loop down a little. Just for effect
usleep(1000000 / 100);
}
// Simple program to recreate an event loop
int main() {
try {
StateExecutor stateExecutor = StateExecutor();
int count = 0;
do {
loop(stateExecutor);
count++;
// Arbitrarily break out of the loop after 100 events.
} while(count < 100);
} catch (std::exception& e){
std::cout << e.what() << '\n';
}
}
Here are the values directly after the factory created them. All looks good.
Gah! I called usleep() and the factoryState's name field is gone and the bools have reverted to true (cout does this as well). Black magic!
Here:
static State* getDefaultState(){
StateReading defaultState = StateReading();
State* state = &defaultState;
return state;
}
You return a pointer to defaultState. This state however is destroyed when the function returns. Using this pointer later is undefined behavior. You can declare defaultState as static, though i would rather make it a static member.

Error "Expected invocation on the mock once, but was 0 times" when unit testing with moq

I have the following class I want to test:
public interface ISqlServiceByModule
{
DataSet GetPagedAggregateData(int clientId, int moduleId, int billTypeId, PagedTable result);
}
public class IncidentModuleService : IIncidentModuleService
{
private readonly ISqlServiceByModule sqlServiceByModule;
public IncidentModuleService(ISqlServiceByModule sqlServiceByModule)
{
if (sqlServiceByModule == null) throw new ArgumentNullException("sqlServiceByModule");
// Inject the ISqlServiceByModule dependency into the constructor
this.sqlServiceByModule = sqlServiceByModule;
}
public PagedTable GetData(int clientId, int moduleId, int billTypeId, Dictionary<string, string> queryStringParameters)
{
PagedTable result = new PagedTable(queryStringParameters);
DataSet dataSet = this.sqlServiceByModule.GetPagedAggregateData(clientId, moduleId, billTypeId, result);
// Map the DatSet to a PagedTable
if (dataSet == null || dataSet.Tables.Count == 0)
{
result.SetPagesFromTotalItems(0);
}
else
{
result.SetPagesFromTotalItems(Convert.ToInt16(dataSet.Tables[1].Rows[0][0]));
result.Listings = dataSet.Tables[0];
}
return result;
}
}
Specifically, I want to test the GetData method. My unit test looks like this:
[TestClass]
public class IncidentModuleServiceUnitTest
{
private DataSet incidentsData;
[TestInitialize]
public void SetUp()
{
this.incidentsData = new DataSet();
}
[TestMethod]
public void GetDataTestGetPagedAggregateDataIsCalled()
{
//-- Arrange
int billTypeId = 1;
int clientId = 1;
int moduleId = 1;
Dictionary<string, string> queryStringParameters = new Dictionary<string,string>();
PagedTable tempResult = new PagedTable(queryStringParameters);
DataSet dataSet = new DataSet();
dataSet.Tables.Add(new DataTable());
var mockSqlService = new Mock<ISqlServiceByModule>();
mockSqlService.Setup(r => r.GetPagedAggregateData(clientId, moduleId, billTypeId, tempResult)).Returns(this.incidentsData);
IncidentModuleService target = new IncidentModuleService(mockSqlService.Object);
//-- Act
var actual = target.GetData(clientId, moduleId, billTypeId, queryStringParameters);
//-- Assert
Assert.IsNull(actual.Listings);
mockSqlService.Verify(r => r.GetPagedAggregateData(clientId, moduleId, billTypeId, tempResult), Times.Once);
}
}
The error I am getting happens on the last line:
mockSqlService.Verify(r => r.GetPagedAggregateData(clientId, moduleId, billTypeId, tempResult), Times.Once);
And the exact error message is this:
{"\r\nExpected invocation on the mock once, but was 0 times: r =>
r.GetPagedAggregateData(.clientId, .moduleId, .billTypeId, .tempResult
Configured setups:\r\nr => r.GetPagedAggregateData(.clientId,
.moduleId, .billTypeId, .tempResult),
Times.Never
Performed invocations:\r\nISqlServiceByModule.GetPagedAggregateData(1,
1, 1, PagedTable)"}
Any idea why this is happening? It looks to me like the method in question is being called, but Moq doesn't like the parameters for some reason, even though they are the exact same ones in all three invocations, as far as I can tell.
PagedTable is a reference type not a value type. Therefore the parameters in Setup don't match what was called even though they look like they should be the same. You could use It.IsAny<PagedTable>() instead of tempResult.
See this answer for an example of how to check that the PagedTable parameter was the correct one.

Spring Data Neo4j 4 : Failed to convert from type java.util.LinkedHashSet<?> to type org.springframework.data.domain.Page<?>

Having this Repository method
#Query("MATCH (i:`Interest`) WHERE not(i-[:PARENT]->()) return i")
public Page<Interest> findAllByParentIsNull(Pageable pageRequest);
It cause (it didn't respect the specification):
org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.util.LinkedHashSet<?> to type org.springframework.data.domain.Page<?> for value '[com.nearofme.model.Interest#12a4479, com.nearofme.model.Interest#15bdfb3, com.nearofme.model.Interest#1af6067, com.nearofme.model.Interest#1c17d4d, com.nearofme.model.Interest#df65f4, com.nearofme.model.Interest#3b140d, com.nearofme.model.Interest#1e24566, com.nearofme.model.Interest#da49c9]'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.util.LinkedHashSet<?> to type org.springframework.data.domain.Page<?>
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:192)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:176)
at org.springframework.data.repository.core.support.QueryExecutionResultHandler.postProcessInvocationResult(QueryExecutionResultHandler.java:75)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:439)
Debugging the code shows that a conversion is needed at the GraphRepositoryQuery level :
#Override
public final Object execute(Object[] parameters) {
Class<?> returnType = graphQueryMethod.getMethod().getReturnType();
Class<?> concreteType = graphQueryMethod.resolveConcreteReturnType();
Map<String, Object> params = resolveParams(parameters);
// could be converted here
return execute(returnType, concreteType, getQueryString(), params);
}
The current code convert the result at GraphRepositoryImpl with the private method updatePage that should be used in the GraphRepositoryQuery
#Override
public Page<T> findAll(Pageable pageable, int depth) {
Collection<T> data = session.loadAll(clazz, convert(pageable.getSort()), new Pagination(pageable.getPageNumber(), pageable.getPageSize()), depth);
return updatePage(pageable, new ArrayList<T>(data));
}
So my current temporary solution is to update GraphRepositoryQuery with :
#Override
public final Object execute(Object[] parameters) {
Class<?> returnType = graphQueryMethod.getMethod().getReturnType();
Class<?> concreteType = graphQueryMethod.resolveConcreteReturnType();
Map<String, Object> params = resolveParams(parameters);
Object result = execute(returnType, concreteType, getQueryString(), params);
if (params.size()>0){
Object param = params.values().toArray()[0];
if (param instanceof Pageable){
Pageable pageable = (Pageable) param;
result = updatePage(pageable, new ArrayList((Collection) result));
}
}
return result;
}
private Page updatePage(Pageable pageable, List results) {
int pageSize = pageable.getPageSize();
int pageOffset = pageable.getOffset();
int total = pageOffset + results.size() + (results.size() == pageSize ? pageSize : 0);
return new PageImpl(results, pageable, total);
}
No more need to convert inside the GraphRepositoryImpl but it still working

Checking list within constructor for duplicates

I have a class called Recipe. The Recipe maynot contain duplicate Ingredients, otherwise a Illegal Argument Exception should be thrown. I tried to use a helplist but I am getting a NullPointerException for the line: "for (int i = 0; i < ingredients.size(); i++)"
public class Recipe {
private String title;
private String instructions;
private LinkedList<Ingredient> ingredients;
boolean noduplicate = true;
// constructor
public Recipe(String title, String instructions,
List<Ingredient> ingredients) {
this.title = title;
this.instructions = instructions;
LinkedList<Ingredient> helplist = new LinkedList<Ingredient>();
for (int i = 0; i < ingredients.size(); i++) {
Ingredient x = ingredients.get(i);
if (helplist.contains(x)) {
noduplicate = false;
throw new IllegalArgumentException(
"This ingredient is duplicate!");
}
if (noduplicate) {
helplist.add(x);
}
noduplicate = true;
}
this.ingredients = helplist;
}
}
Use a set instead of a list, since that is the datastructure you want. In short, a set only contains unique elements. When you try to add stuff which is already there, nothing happens. You have to override the equal/hash method of your Ingredients class in order to make it work.
http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

call c++ function in Java with input and output arguments

I have a c++ code which has been connected to a visual basic user interface by someone else. Here is one of the functions code that connects c++ to visual basic:
extern "C" void PASCAL EXPORT RCS( stAct* act,stResourceDirectory* resDir, stCalendar* calendar, short numOfAct, short numOfRes, short numOfCal, int nDataDate )
{
Network network;
short id;
Activity* p_act;
node<Activity>* p_node;
// Setting
network.create_calendars (calendar, numOfCal);
network.set_data_date (nDataDate);
set_activity(network, act, numOfAct );
// only for id, duration, and description
set_resource(network, act, resDir, numOfAct, numOfRes);
// create resource profile and add required resource for every activity
network.CPM ();
p_node = network.get_network_head_p();
while (p_node != NULL ) {
p_act = p_node->refer_data();
id = p_act->get_ID ();
act[id].TF_in_CPM = p_act->get_TF_min ();
act[id].FF_in_CPM = p_act->get_FF();
act[id].EST_in_CPM = p_act->get_EST ();
act[id].EFT_in_CPM = p_act->get_EFT ();
act[id].LST_in_CPM = p_act->get_LST ();
act[id].LFT_in_CPM = p_act->get_LFT ();
p_node = p_node->get_link();
}
network.RCS();
p_node = network.get_network_head_p();
while (p_node != NULL ) {
p_act = p_node->refer_data();
id = p_act->get_ID ();
act[id].TF_in_RCS = p_act->get_TF_min ();
act[id].FF_in_RCS = p_act->get_FF();
act[id].EST_in_RCS = p_act->get_EST ();
act[id].EFT_in_RCS = p_act->get_EFT ();
act[id].LST_in_RCS = p_act->get_LST ();
act[id].LFT_in_RCS = p_act->get_LFT ();
p_node = p_node->get_link();
}
}
I want to replace the visual basic part with a Java GUI and it seems confusing for me to write the connection code. Is there anyone who can help me call three c++ functions with passing arguments to the native method and receiving results from it, by JNA/ SWIG/ Runtime or any other methods you think it would work easier and better?
Here is an instructional example to help get you started. In this snippet, Java2Win64 is the DLL that contains the native code to execute. Function functionMaryam() takes 1 param as int and returns an int. Easy to expand for any data type.
public class JnaExampleMaryam {
// ------------------------------------------
// Java2Win.class
// ------------------------------------------
public interface Java2Win extends Library {
Java2Win call = (Java2Win) Native.loadLibrary("Java2Win64", Java2Win.class);
int functionMaryam(int i);
}
// ------------------------------------------
// ------------------------------------------
// Test
// ------------------------------------------
public static void main(final String args[]) throws Exception {
final File file = new File("rootToDLL", "Java2Win64.dll");
LibraryLoader.loadLibrary(file);
int result = Java2Win.call.functionMaryam(42);
}
// ------------------------------------------