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 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
Is it possible to perform unittest tests via a web interface...and if so how?
EDIT:
For now I want the results...for the tests I want them to be automated...possibly every time I make a change to the code. Sorry I forgot to make this more clear
for metrics reasons I need to know how many lines of code my class library has. I'm doing this for code coverage....
So if Class library 1 has 50 lines of code and 100% coverage
And if Class library 2 has 500 lines of code and 0% coverage
My total coverage is 90%
Any idea how to do this? Is there a utility or a way to use Visual Studio?
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.
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... ?
I have two classes:
public abstract class AbstractFoobar { ... }
and
public class ConcreteFoobar extends AbstractFoobar { ... }
I have corresponding test classes for these two classes:
public class AbstractFoobarTest { ... }
and
public class ConcreteFoobarTest extends AbstractFoobarTest { ... }
When I run ConcreteFoobarTest (in JUnit), the annotated @Test methods in AbstractFoobarTest get run along with those declared directly on ConcreteFoobarTest because they are inherited.
Is there anyway to skip them?
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();
}
There is a simple controller that a querystring is read in constructor of it.
public class ProductController : Controller
{
parivate string productName;
public ProductController()
{
productName = Request.QueryString["productname"];
}
public ActionResult Index()
{
ViewData["Message"] = productName;
return View();
}
}
Also I have a function in unit test that create an instance of this Controller and I fill the querystring by a Mock object like below.
[TestClass]
public class ProductControllerTest
{
[TestMethod]
public void test()
{
// Arrange
var querystring = new System.Collections.Specialized.NameValueCollection { { "productname", "sampleproduct"} };
var mock = new Mock<ControllerContext>();
mock.SetupGet(p => p.HttpContext.Request.QueryString).Returns(querystring);
var controller = new ProductController();
controller.ControllerContext = mock.Object;
// Act
var result = controller.Index() as ViewResult;
// Assert
Assert.AreEqual("Index", result.ViewName);
}
}
Unfortunately Request.QueryString["productname"] is null in constructor of ProductController when I run test unit.
Is ther any way to fill a querystrin by a mocking and get it in constructor of a control?
We have splitted our grails application into several inplace-plugins.
Now we want to have the tests in the same plugin like the classes which they test.
Is it possible to configure our application (e.g. in BuildConfig.groovy) so that the tests in the plugins are executed too when we run "test-app"?
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
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.
I am quite new to TDD and am going with NUnit and Moq. I have got a method where I expect an exception, so I wanted to play a little with the frameworks features.
My test code looks as follows:
[Test]
[ExpectedException(ExpectedException = typeof(MockException), ExpectedMessage = "Actual differs from expected")]
public void Write_MessageLogWithCategoryInfoFail()
{
string message = "Info Test Message";
Write_MessageLogWithCategory(message, "Info");
_LogTest.Verify(writeMessage =>
writeMessage.Info("This should fail"),
"Actual differs from expected"
);
}
But I always receive the errormessage that the error message that the actual exception message differs from the expected message. What am I doing wrong?
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.
We have a number of integration tests that fail when our staging server goes down for weekly maintenance. When the staging server is down we send a specific response that I could detect in my integration tests. When I get this response instead of failing the tests I'm wondering if it is possible to skip/ignore that test even though it has started running. This would keep our test reports a bit cleaner.
Does anybody have suggestions?
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 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.
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 have a class ClassToTest which has a dependency on ClassToMock.
public class ClassToMock {
private static final String MEMBER_1 = FileReader.readMemeber1();
protected void someMethod() {
...
}
}
The unit test case for ClassToTest.
public class ClassToTestTest {
private ClassToMock _mock;
@Before
public void setUp() throws Exception {
_mock = mock(ClassToMock.class)
}
}
When mock is called in the setUp() method, FileReader.readMemeber1(); is executed. Is there a way to avoid this? I think one way is to initialize the MEMBER_1 inside a method. Any other alternatives?
Thanks!
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.
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?
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.
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.