I could not confirm whether to do these tests. It seems the set and get method is so simple,such as:
setA(String A) {
this.A = A;
}
getA(){
return A;
}
Any ideas would be appreciated!
Thanks,
Joseph
How do you know if you "Test Fixture" is right-sized. And by "Test Fixture" I mean a class with a bunch of tests in it.
One thing that I've always noticed with my test fixtures is that they get to be kind of verbose; seeing as they could also be not verbose enough, how do you get a sense of when your unit tests are the right size?
My assumption is that (at least in the context of web development) you should have one test fixture class per page.
I know of a good quote for this and it's:
"Perfection is achieved, not when there is nothing left to add, but when there is nothing left to remove." - Antoine de Saint-Exupery.
We are writing unit tests for our ASP.NET application that run against a test SQL Server database.
That is, the ClassInitialize method creates a new database with test data, and the ClassCleanup deletes the database. We do this by running .bat scripts from code.
The classes under test are given a connection string that connects to the unit test database rather than a production database.
Our problem is, that the database contains a full text index, which needs to be fully populated with the test data in order for our tests to run as expected.
As far as I can tell, the fulltext index is always populated in the background. I would like to be able to either:
Create the full text index, fully populated, with a synchronous (transact-SQL?) statement, or
Find out when the fulltext population is finished, is there a callback option, or can I ask repeatedly?
My current solution is to force a delay at the end the class initialize method - 5 seconds seems to work - because I can't find anything in the documentation.
In Junit 4, do you see any drawback to throw a ComparisonFailure instead of an AssertionError when assertEquals(Object, Object) fails ?
assertEquals(Object, Object) throws
a ComparisonFailure if both expected and actual are String
an AssertionError if either is not a String
@Test(expected=ComparisonFailure.class )
public void twoString() {
assertEquals("a String", "another String");
}
@Test(expected=AssertionError.class )
public void oneString() {
assertEquals("a String", new Object());
}
The two reasons why I ask the question:
ComparisonFailure provide far more readable way to spot the differences in dialog box of eclipse or Intellij IDEA (FEST-Assert throws this exception)
Junit 4 already use String.valueOf(Object) to build message "expected ... but was ..." (format method invoqued by Assert.assertEquals(message, Object, Object) in junit-4.8.2):
static String format(String message, Object expected, Object actual) {
...
String expectedString= String.valueOf(expected);
String actualString= String.valueOf(actual);
if (expectedString.equals(actualString))
return formatted + "expected: "
+ formatClassAndValue(expected, expectedString) +" but was: "
+ formatClassAndValue(actual, actualString);
else
return formatted +"expected:<"+ expectedString +"> but was:<"+ actualString +">";
Isn't it possible in assertEquals(message, Object, Object) to replace
fail(format(message, expected, actual));
by
throw new ComparisonFailure(message,
formatClassAndValue(expectedObject, expectedString),
formatClassAndValue(actualObject, actualString));
Do you see any compatibility issue with other tool, any algorithmic problem with that... ?
This is also a question that I asked in a comment in one of Miško Hevery's google talks that was dealing with dependency injection but it got buried in the comments.
I wonder how can the factory / builder step of wiring the dependencies together can work in C++.
I.e. we have a class A that depends on B. The builder will allocate B in the heap, pass a pointer to B in A's constructor while also allocating in the heap and return a pointer to A.
Who cleans up afterwards? Is it good to let the builder clean up after it's done? It seems to be the correct method since in the talk it says that the builder should setup objects that are expected to have the same lifetime or at least the dependencies have longer lifetime (I also have a question on that). What I mean in code:
class builder {
public:
builder() :
m_ClassA(NULL),m_ClassB(NULL) {
}
~builder() {
if (m_ClassB) {
delete m_ClassB;
}
if (m_ClassA) {
delete m_ClassA;
}
}
ClassA *build() {
m_ClassB = new class B;
m_ClassA = new class A(m_ClassB);
return m_ClassA;
}
};
Now if there is a dependency that is expected to last longer than the lifetime of the object we are injecting it into (say ClassC is that dependency) I understand that we should change the build method to something like:
ClassA *builder::build(ClassC *classC) {
m_ClassB = new class B;
m_ClassA = new class A(m_ClassB, classC);
return m_ClassA;
}
What is your preferred approach?
I recently obtained a Mac so I could test our sites on Safari and Firefox for Mac OS.
Now that Safari 5 is out, I'm not sure what I should do about upgrading. I presume what works on Safari 5 works on Safari 4, but I can't be sure, and vice versa. So, I don't know if I should upgrade and test on Safari 5 or keep on with Safari 4.
Are there any major differences between these two version in terms of CSS (2.1) handling or JavaScript? When do you think the majority of people will have Safari 5 instead of 4?
All thoughts appreciated.
I'm unable to run any selenium tests since I updated Firefox to 3.6. Is it happening just to me or is it everybody?
Error message I get is: Could not start Selenium session: Failed to start browser session
Can anyone help me explain how TimeProvider.Current can become null in the following class?
public abstract class TimeProvider
{
private static TimeProvider current =
DefaultTimeProvider.Instance;
public static TimeProvider Current
{
get { return TimeProvider.current; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
TimeProvider.current = value;
}
}
public abstract DateTime UtcNow { get; }
public static void ResetToDefault()
{
TimeProvider.current = DefaultTimeProvider.Instance;
}
}
Observations
All unit tests that directly reference TimeProvider also invokes ResetToDefault() in their Fixture Teardown.
There is no multithreaded code involved.
Once in a while, one of the unit tests fail because TimeProvider.Current is null (NullReferenceException is thrown).
This only happens when I run the entire suite, but not when I just run a single unit test, suggesting to me that there is some subtle test interdependence going on.
It happens approximately once every five or six test runs.
When a failure occurs, it seems to be occuring in the first executed tests that involves TimeProvider.Current.
More than one test can fail, but only one fails in a given test run.
FWIW, here's the DefaultTimeProvider class as well:
public class DefaultTimeProvider : TimeProvider
{
private readonly static DefaultTimeProvider instance =
new DefaultTimeProvider();
private DefaultTimeProvider() { }
public override DateTime UtcNow
{
get { return DateTime.UtcNow; }
}
public static DefaultTimeProvider Instance
{
get { return DefaultTimeProvider.instance; }
}
}
I suspect that there's some subtle interplay going on with static initialization where the runtime is actually allowed to access TimeProvider.Current before all static initialization has finished, but I can't quite put my finger on it.
Any help is appreciated.
Here is the mysterious:
I have a scope which looks like this (in Image.rb)
scope :moderate_all, delegates.where("moderation_flag = #{$moderation_flags[:not_moderated]}")
Note that delegates is another scope that I am defining before moderate_all
When I leave it like this, I can run my test that checks if an image has been "checked-out" it is not available anymore. I don't put the code of the test, because it does not matter actually.
With this code, when I run "rake test" it fails, but if I do "ruby test/unit/image_test.rb" it works! I was thinking I am starting to have a bad day. Then I tried
scope :moderate_all, lambda {
delegates.where("moderation_flag = #{$moderation_flags[:not_moderated]}")
}
And "rake test" passes!
So my problem is solved, but why?
I need a URL to just test basic http connectivity. It needs to be consistent and:
Always be up
Never change drastically due to IP or user agent. (IE: 301 Location redirect/ huge difference in content... minor would be tolerable)
The URL itself has a consistent content-length. (IE: it doesn't vary from by 2kb at most, ever)
A few examples, yet none match all 3 criteria:
One example of always up: www.google.com (yet it 301 redirects based on IP location).
Another good one is http://www.google.com/webhp?hl=en. but the problem there is that based on a given holiday, the content-length can really vary.
Hello all,
I am currently developing a location based iPhone application. Is there any way to test the app other than taking the iPhone to different places?
Thanks
I was tinkering with doing the setups with our unit test specifciations which go like
Specification for SUT when behaviour X happens in scenario Y
Given that this thing
And also this other thing
When I do X...
Then It should do ...
And It should also do ...
I wrapped each of the steps of the GivenThat in Actions... any feed back whether separating with Actions is good / bad / or better way to make the GivenThat clear?
/// <summary>
/// Given a product is setup for injection
/// And Product Image Factory Is Stubbed();
/// And Product Size Is Stubbed();
/// And Drawing Scale Is Stubbed();
/// And Product Type Is Stubbed();
/// </summary>
protected override void GivenThat()
{
base.GivenThat();
Action givenThatAProductIsSetupforInjection = () =>
{
var randomGenerator = new RandomGenerator();
this.Position = randomGenerator.Generate<Point>();
this.Product = new Diffuser
{
Size =
new RectangularProductSize(
2.Inches()),
Position = this.Position,
ProductType =
Dep<IProductType>()
};
};
Action andProductImageFactoryIsStubbed = () => Dep<IProductBitmapImageFactory>().Stub(f => f.GetInstance(Dep<IProductType>())).Return(ExpectedBitmapImage);
Action andProductSizeIsStubbed = () =>
{
Stub<IDisplacementProduct, IProductSize>(p => p.Size);
var productBounds = new ProductBounds(Width.Feet(), Height.Feet());
Dep<IProductSize>().Stub(s => s.Bounds).Return(productBounds);
};
Action andDrawingScaleIsStubbed = () => Dep<IDrawingScale>().Stub(s => s.PixelsPerFoot).Return(PixelsPerFoot);
Action andProductTypeIsStubbed = () => Stub<IDisplacementProduct, IProductType>(p => p.ProductType);
givenThatAProductIsSetupforInjection();
andProductImageFactoryIsStubbed();
andProductSizeIsStubbed();
andDrawingScaleIsStubbed();
andProductTypeIsStubbed();
}
Is there any good framework for comparing whole objects?
now i do
assertEquals("[email protected]", obj.email);
assertEquals("5", obj.shop);
if bad email is returned i never get to know if it had the right shop, i would like to get a list of incorrect fields.
I ran testng tests for my test classes,
I get the following three types of log output when I run the passing tests.
I am using org.testng.AssertJUnit.assertTrue() methods in my tests.
[testng] PASSED: testMethod1 on null(test.foo.bar.Class1)
[testng] PASSED: testMethod2 on Default test name(test.foo.bar.jar.Class2)
[testng] PASSED: testMethod3
Can any one please tell me why for some tests it says "on null" for some it says "on Default test name ... " and for some it does not say anything on the console output.
Specifically I want to make it consistent message.
Environment : linux
Testng framework : 6.3.2beta
please advise.
thanks.
I'm trying to modify my test projuect to allow for remote invocation of an api we're building. Right now the tests are hard coded to run locally(against localhost), but I would like to be able to point the tests at any endpoint (even remote ones in production).
Ideally there would be a place in the .testsettings for config values to be stored. Sadly this isn't the case.
Or, being able to pass parameters to MSTest that the test would read...?
Any ideas? Thanks in advance.
Hi,
I am using the Google Application Engine plugin for Eclipse 3.4, and I have added unit tests in my projects.
The unit tests are in a source folder named tests, separated from the source folder src.
But, in the war/classes that is generated, the tests classes are present.
Is there anyway not to put test classes in the generated war/classes directory?
Thanks.
I've create a method that calculates the harmonic mean based on a list of doubles.
But when I'm running the test it keeps failing even thou the output result are the same.
My harmonic mean method:
public static double GetHarmonicMean(List<double> parameters)
{
var cumReciprocal = 0.0d;
var countN = parameters.Count;
foreach( var param in parameters)
{
cumReciprocal += 1.0d/param;
}
return 1.0d/(cumReciprocal/countN);
}
My test method:
[TestMethod()]
public void GetHarmonicMeanTest()
{
var parameters = new List<double> { 1.5d, 2.3d, 2.9d, 1.9d, 5.6d };
const double expected = 2.32432293165495;
var actual = OwnFunctions.GetHarmonicMean(parameters);
Assert.AreEqual(expected, actual);
}
After running the test the following message is showing:
Assert.AreEqual failed. Expected:<2.32432293165495. Actual:<2.32432293165495.
For me that are both the same values.
Can somebody explain this? Or am I doing something wrong?
I am using JUnit to write some higher level tests for legacy code that does not have unit tests.
Much of this code "swallows" a variety of unchecked exceptions like NullPointerExceptions (e.g., by just printing stack trace and returning null). Therefore the unit test can pass even through there is a cascade of disasters at various points in the lower level code.
Is there any way to have a test fail on the first unchecked exception even if they are swallowed?
The only alternative I can think of is to write a custom JUnit wrapper that redirects System.err and then analyzes the output for exceptions.
There are two directories in a clojure project - src/ and test/.
There's a file my_methods.clj in the src/calc/ directory which starts with
(ns calc.my_methods...).
I want to create a test file for it in test directory - test/my_methods-test.clj
(ns test.my_methods-test
(:require [calc.my_methods])
(:use clojure.test))
In the $CLASSPATH there are both project root directory and src/ directory. But the exception is still
"Could not locate calc/my_methods__init.class or calc/my_methods.clj on classpath". What is the problem with requiring it in the test file?
echo $CLASSPATH gives this:
~/project:~/project/src
Is it better to write/record selenium tests in html format and run them directly in the server with "-htmlSuite" or to write the tests in java/C#/... and run them in the server using selenium-rc?
What is the recommended solution?
So I had a class that referenced a class that referenced another class that called a web service.
So I learn how to create an interface using partial classes.
I inject the web service through the constructor.
Then my unit test fails because I am newing up the actual web service in the second level of the class. So I end up modifying all three classes to pass the web service down through the constructor... was not happy :-( gave up....
what should I be doing in this case?
People are still wondering what are the differences between the two most popular unit testing frameworks in the .NET world: the open source NUnit and the commercial MsTest). Heres a short list of what i remember instantly: Nunit contains a [TestCase] attribute that allows implementing parametrized tests. this does not exist in msTest MsTest's ExpectedException attribute has a bug where the expected message is never really asserted even if it's wrong - the test will pass. Nunit has an...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.
UPDATE: I've changed the wording of the question. Previously it was a yes/no question about if a base class could be changed at runtime.
I may be working on mission impossible here, but I seem to be getting close. I want to extend a ASP.NET control, and I want my code to be unit testable. Also, I'd like to be able to fake behaviors of a real Label (namely things like ID generation, etc), which a real Label can't do in an nUnit host.
Here a working example that makes assertions on something that depends on a real base class and something that doesn't-- in a more realistic unit test, the test would depend on both --i.e. an ID existing and some custom behavior.
Anyhow the code says it better than I can:
public class LabelWrapper : Label //Runtime
//public class LabelWrapper : FakeLabel //Unit Test time
{
private readonly LabelLogic logic= new LabelLogic();
public override string Text
{
get
{
return logic.ProcessGetText(base.Text);
}
set
{
base.Text=logic.ProcessSetText(value);
}
}
}
//Ugh, now I have to test FakeLabelWrapper
public class FakeLabelWrapper : FakeLabel //Unit Test time
{
private readonly LabelLogic logic= new LabelLogic();
public override string Text
{
get
{
return logic.ProcessGetText(base.Text);
}
set
{
base.Text=logic.ProcessSetText(value);
}
}
}
[TestFixture]
public class UnitTest
{
[Test]
public void Test()
{
//Wish this was LabelWrapper label = new LabelWrapper(new FakeBase())
LabelWrapper label = new LabelWrapper();
//FakeLabelWrapper label = new FakeLabelWrapper();
label.Text = "ToUpper";
Assert.AreEqual("TOUPPER",label.Text);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringWriter);
label.RenderControl(writer);
Assert.AreEqual(1,label.ID);
Assert.AreEqual("<span>TOUPPER</span>", stringWriter.ToString());
}
}
public class FakeLabel
{
virtual public string Text { get; set; }
public void RenderControl(TextWriter writer)
{
writer.Write("<span>" + Text + "</span>");
}
}
//System Under Test
internal class LabelLogic
{
internal string ProcessGetText(string value)
{
return value.ToUpper();
}
internal string ProcessSetText(string value)
{
return value.ToUpper();
}
}