Hi,
I want to test an "Adapter" object that when it receives an xml message,
it digest it to a Message object, puts message ID + CorrelationID both
with timestamps and forwards it to a Client object.=20
A message can be correlated to a previous one (e.g. m2.correlationID =3D
m1.ID).
I mock the Client, and check that Adapter successfully calls
"client.forwardMessage(m)" twice with first message with null
correlationID, and a second with a not-null correlationID.
However, I would like to precisely test that the correlationIDs are set
correctly, by grabing the IDs (e.g. m1.ID).
But I couldn't find anyway to do so.
There is a jira about adding the feature, but no one commented and it
is unassigned.
Is this really unimplemented?
I read about the alternative of redesigning the Adapter to use an
IdGenerator object, which I can stub, but I think there will be too many
objects.=20
Don't you think it adds unnecessary complexity to split objects to a so
fine granularity?
Thanks, and I appreciate any comments :-)
Tayeb
I'm using webflows in Grails and I'm currently writing tests for it. Now, inside I've got something that throws an error so I set a message to the flash scope before redirecting:
...
if (some_condition) {
flash.message = "my error message"
return error()
}
...
Now, I know that when I'm going to display this in the GSP page, I access the flash message as
<g:if test="${message}">...
instead of the usual
<g:if test="${flash.message}">...
So anyway, I'm writing my test and I'm wondering how to test the content of the message? Usually, in normal actions in the controllers, I follow what's written in here . However, since this is a webflow, I can't seem to find the message even if I check controller.flash.message / controller.params.message / controller.message . I've also tried looking at the flow scope...
Any ideas on how to see the message then? Thanks a bunch!
Hi to all,
When i test the execution of a method that creates a child thread, the JUnit test ends before the child thread and kills it.
How do i force JUnit to wait for the child thread to complete its execution?
Thanks
The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own test directory:
new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
for example see this Python project howto.
My question is simply What's the usual way of actually running the tests? I suspect this is obvious to everyone except me, but you can't just run python test_antigravity.py from the test directory as its import antigravity will fail as the module is not on the path.
I know I could modify PYTHONPATH and other search path related tricks, but I can't believe that's the simplest way - it's fine if you're the developer but not realistic to expect your users to use if they just want to check the tests are passing.
The other alternative is just to copy the test file into the other directory, but it seems a bit dumb and misses the point of having them in a separate directory to start with.
So, if you had just downloaded the source to my new project how would you run the unit tests? I'd prefer an answer that would let me say to my users: "To run the unit tests do X."
I want to load to new AppDomin some assembly which has a complex references tree (MyDll.dll - Microsoft.Office.Interop.Excel.dll - Microsoft.Vbe.Interop.dll - Office.dll - stdole.dll)
As far as I understood, when an assembly is been loaded to AppDomain, it's references would not be loaded automatically, and I have to load them manually.
So when I do:
string dir = @"SomePath"; // different from AppDomain.CurrentDomain.BaseDirectory
string path = System.IO.Path.Combine(dir, "MyDll.dll");
AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
setup.ApplicationBase = dir;
AppDomain domain = AppDomain.CreateDomain("SomeAppDomain", null, setup);
domain.Load(AssemblyName.GetAssemblyName(path));
and got FileNotFoundException:
Could not load file or assembly 'MyDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
I think the key word is one of its dependencies.
Ok, I do next before domain.Load(AssemblyName.GetAssemblyName(path));
foreach (AssemblyName refAsmName in Assembly.ReflectionOnlyLoadFrom(path).GetReferencedAssemblies())
{
domain.Load(refAsmName);
}
But got FileNotFoundException again, on another (referenced) assembly.
How to load all references recursively?
Have I to create references tree before loading root assembly? How to get an assembly's references without loading it?
What options do I have to automate tests for the various aspects of my custom WPF controls, such as:
Layout behavior
input and user interaction behavior
general apperance
I have a whole bunch of unit tests written in MbUnit and I would like to generate plain English sentences from test names. The concept is introduced here:
http://dannorth.net/introducing-bdd
This is from the article:
public class CustomerLookupTest extends TestCase {
testFindsCustomerById() {
...
}
testFailsForDuplicateCustomers() {
...
}
...
}
renders something like this:
CustomerLookup
- finds customer by id
- fails for duplicate customers
- ...
Unfortunately the tool quoted in the above article (testdox) is Java based. Is there one for .NET?
Sounds like this would be something pretty simple to write, but I simply don't have the bandwidth and want to use something already written.
I'm using Django Internationalization tools to translate some strings from my application. The code looks like this:
from django.utils.translation import ugettext as _
def my_view(request):
output = _("Welcome to my site.")
return HttpResponse(output)
Then, I'm writing unit tests using the Django test client. These tests make a request to the view and compare the returned contents.
How can I disable the translations while running the unit tests? I'm aiming to do this:
class FoobarTestCase(unittest.TestCase):
def setUp(self):
# Do something here to disable the string translation. But what?
# I've already tried this, but it didn't work:
django.utils.translation.deactivate_all()
def testFoobar(self):
c = Client()
response = c.get("/foobar")
# I want to compare to the original string without translations.
self.assertEquals(response.content.strip(), "Welcome to my site.")
We're working with some very large config files which contain lots of Unity and WCF configuration.
When we open some of these configs in the SVC config editor or even try to open a web application using these configs, we recieve errors showing any typos or errors. E.g. a WCF binding is invalid or does not exist etc, or a configuration section does not exist, two endding tags, etc.
Is there some way to "valid" a config through a unit test? So there's one less thing which could go wrong when the application is moved into a new environment.
I'm trying to build a test framework for automated webtesting in selenium and unittest, and I want to structure my tests into distinct scripts. So I've organised it as following:
base.py - This will contain, for now, the base selenium test case class for setting up a session.
import unittest
from selenium import webdriver
# Base Selenium Test class from which all test cases inherit.
class BaseSeleniumTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
self.browser.close()
main.py - I want this to be the overall test suite from which all the individual tests are run.
import unittest
import test_example
if __name__ == "__main__":
SeTestSuite = test_example.TitleSpelling()
unittest.TextTestRunner(verbosity=2).run(SeTestSuite)
test_example.py - An example test case, it might be nice to make these run on their own too.
from base import BaseSeleniumTest
# Test the spelling of the title
class TitleSpelling(BaseSeleniumTest):
def test_a(self):
self.assertTrue(False)
def test_b(self):
self.assertTrue(True)
The problem is that when I run main.py I get the following error:
Traceback (most recent call last):
File "H:\Python\testframework\main.py", line 5, in <module>
SeTestSuite = test_example.TitleSpelling()
File "C:\Python27\lib\unittest\case.py", line 191, in __init__
(self.__class__, methodName))
ValueError: no such test method in <class 'test_example.TitleSpelling'>: runTest
I suspect this is due to the very special way in which unittest runs and I must have missed a trick on how the docs expect me to structure my tests. Any pointers?
Very often I hear: use profiler, do unit test. How to do it? I would be glad if someone would provide either links to websites with tutorials or recommend a good book. I'm using Visual Studio 2010 Ultimate.
I've come across odd behavior when comparing strings. First assert passes, but I don't think it should.. Second assert fails, as expected...
[Fact]
public void StringTest()
{
string testString_1 = "My name is Erl. I am a program\0";
string testString_2 = "My name is Erl. I am a program";
Assert.Equal<string>(testString_1, testString_2);
Assert.True(testString_1.Equals(testString_2));
}
Any ideas?
Hi,
I have a few classes in the class library (separate assembly). I referenced it to my project and I want to initialize one specific class from that library. I know only its name. All of the classes implements one interface.
And here comes the problem.
My code so far:
using MyLibrary;
...
IMyInterface dll = Activator.CreateInstance("MyLibrary", "MyLibrary.NameOfClass") as IMyInterface;
But dll is always null.
Any ideas?
Thanks
I'm having trouble getting frontend cookie capture to work in haproxy. I have this in my config:
frontend frontend 0.0.0.0:9999
[snip]
capture cookie foo len 10
Then I use nc to talk directly to the server and send it:
GET / HTTP/1.1
Cookie: foo=bar
I get a log line, but there's a "-" where the captured cookie should be.
I'm working on writing various things that call relatively complicated Win32 API functions. Here's an example:
//Encapsulates calling NtQuerySystemInformation buffer management.
WindowsApi::AutoArray NtDll::NtQuerySystemInformation(
SystemInformationClass toGet ) const
{
AutoArray result;
ULONG allocationSize = 1024;
ULONG previousSize;
NTSTATUS errorCheck;
do
{
previousSize = allocationSize;
result.Allocate(allocationSize);
errorCheck = WinQuerySystemInformation(toGet,
result.GetAs<void>(), allocationSize, &allocationSize);
if (allocationSize <= previousSize)
allocationSize = previousSize * 2;
} while (errorCheck == 0xC0000004L);
if (errorCheck != 0)
{
THROW_MANUAL_WINDOWS_ERROR(WinRtlNtStatusToDosError(errorCheck));
}
return result;
}
//Client of the above.
ProcessSnapshot::ProcessSnapshot()
{
using Dll::NtDll;
NtDll ntdll;
AutoArray systemInfoBuffer = ntdll.NtQuerySystemInformation(
NtDll::SystemProcessInformation);
BYTE * currentPtr = systemInfoBuffer.GetAs<BYTE>();
//Loop through the results, creating Process objects.
SYSTEM_PROCESSES * asSysInfo;
do
{
// Loop book keeping
asSysInfo = reinterpret_cast<SYSTEM_PROCESSES *>(currentPtr);
currentPtr += asSysInfo->NextEntryDelta;
//Create the process for the current iteration and fill it with data.
std::auto_ptr<ProcImpl> currentProc(ProcFactory(
static_cast<unsigned __int32>(asSysInfo->ProcessId), this));
NormalProcess* nptr = dynamic_cast<NormalProcess*>(currentProc.get());
if (nptr)
{
nptr->SetProcessName(asSysInfo->ProcessName);
}
// Populate process threads
for(ULONG idx = 0; idx < asSysInfo->ThreadCount; ++idx)
{
SYSTEM_THREADS& sysThread = asSysInfo->Threads[idx];
Thread thread(
currentProc.get(),
static_cast<unsigned __int32>(sysThread.ClientId.UniqueThread),
sysThread.StartAddress);
currentProc->AddThread(thread);
}
processes.push_back(currentProc);
} while(asSysInfo->NextEntryDelta != 0);
}
My problem is in mocking out the NtDll::NtQuerySystemInformation method -- namely, that the data structure returned is complicated (Well, here it's actually relatively simple but it can be complicated), and writing a test which builds the data structure like the API call does can take 5-6 times as long as writing the code that uses the API.
What I'd like to do is take a call to the API, and record it somehow, so that I can return that recorded value to the code under test without actually calling the API. The returned structures cannot simply be memcpy'd, because they often contain inner pointers (pointers to other locations in the same buffer). The library in question would need to check for these kinds of things, and be able to restore pointer values to a similar buffer upon replay. (i.e. check each pointer sized value if it could be interpreted as a pointer within the buffer, change that to an offset, and remember to change it back to a pointer on replay -- a false positive rate here is acceptable)
Is there anything out there that does anything like this?
Hello,
I am a ruby and rails newbie. And I am working on a rails application with RadRails. RadRails has a "Switch to Test" function for my controller, model, etc. but not for my library. if I have class Foo::Bar in /lib/foo/bar.rb, where should I put the unittest for it?
or should I separate the foo library in a separated project?
Thanks.
This seems like an easy enough issue but I can't seem to find the keywords to effect my searches.
I'm trying to unit test by mocking out all objects within this method call. I am able to do so to all of my own creations except for this one:
public void MyFunc(MyVarClass myVar)
{
Image picture;
...
picture = Image.FromStream(new MemoryStream(myVar.ImageStream));
...
}
FromStream is a static call from the Image class (part of c#). So how can I refactor my code to mock this out because I really don't want to provide a image stream to the unit test.
I got this event handle and how can I do unit test for this
public class MyLearningEvent
{
private event EventHandler _Closed;
public event EventHandler Closed
{
add
{
_Closed -= value;
_Closed += value;
}
remove
{
_Closed -= value;
}
}
public void OnClosed()
{
if (_Closed != null) _Closed(this, EventArgs.Empty);
}
}
Just modified code so that much clear
Thanks
I have something like
- (void)getData:(SomeParameter*)param
{
// Remotely call out for data returned asynchronously
// returns data via a delegate method
}
- (void)handleDataDelegateMethod:(NSData*)data
{
// Handle returned data
}
I want to write a unit test for this, how can I do something better than
NSData* returnedData = nil;
- (void)handleDataDelegateMethod:(NSData*)data
{
returnedData = data;
}
- (void)test
{
[obj getData:param];
while (!returnedData)
{
[NSThread sleep:1];
}
// Make tests on returnedData
}
i have this querystring that shall open up my page.
http://www.a1-one.com/[email protected]&stuid=123456
Now when this page loads, on page_load, I want to pick up email and stuid in two different variables. So I can use them to insert into my database (sql server)
how can this be done in vb.net
When I select an NUnit test in the Unit Test Sessions window and click debug, the window disappears. My breakpoints are hit, but if I hit F5, the Unit Test Sessions window does not return until the test returns a result or I stop the debugging session. This is preventing me from viewing any console output during tests. Any ideas?
I'm writing many unit tests in VS 2010 with Microsoft Test. In each test class I have many test methods similar to below:
[TestMethod]
public void This_is_a_Test()
{
try
{
// do some test here
// assert
}
catch (Exception ex)
{
// test failed, log error message in my log file and make the test fail
}
finally
{
// do some cleanup with different parameters
}
}
When each test method looks like this I fell it's kind of ugly. But so far I haven't found a good solution to make my test code more clean, especially the cleanup code in the finally block. Could someone here give me some advices on this?
Thanks in advance.
We have a function which accesses two types of controls like button and list box in standard windows app. The function uses only the control name as arguments, so there is no way qtp could understand what type of control it is. how to resolve this? Write 2 separate functions- 1 for button & another for list box?