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?
I'm running my unit tests on a piece of code that does the following in the test:
Assert.IsNotNull(target.Icon);
Inside the getter for the Icon property, I'm doing this:
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
That's throwing this exception: System.InvalidOperationException : The calling thread must be STA, because many UI components require this.
I understand what that means, and I understand that I need to use the Dispatcher, but I'm a bit confused about how or why... this is a property of my ViewModel and I don't get any of these exceptions when running the application.
Other info: this only started failing when I upgraded to .NET 4.
I have a visual studio load test which I want to run every hour so that I can start to collect some data.
To do this, I thought it would be best to make a little powershell script and put a command like this inside:
Invoke-Expression -command "& '$env:VS100COMNTOOLS..\IDE\mstest.exe'
/testcontainer:"C:\Users\benb\Documents\Visual Studio
2010\Projects\BBPerformanceTest\bin\Debug\HomePageOnly.loadtest""
That command works fine, but sometimes when its run I get a blue screen of death. However, when I run my load test through the visual studio GUI, I never get a BSOD.
two questions:
is it possible to avoid this BSOD?
Is there another way I can schedule my load test?
Thanks
In TDD(Test Driven Development) development process, how to deal with the test data?
Assumption that a scenario, parse a log file to get the needed column. For a strong test, How do I prepare the test data? And is it properly for me locate such files to the test class files?
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,
I have the following test method (VB.NET)
<RowTest()> _
<Row(1, 2, 3)> _
Public Sub AddMultipleNumbers(ByVal number1 As Integer, ByVal number2 As Integer, ByVal result As Integer)
Dim dvbc As VbClass = New VbClass()
Dim actual As Integer = dvbc.Add(number1, number2)
Assert.That(actual, [Is].SameAs(result))
End Sub
My problem is that when the test runs, using TestDriven.Net, the three method parameters are 0 and not the values I am expecting. I have referenced the NUnit.Framework (v.2.5.3.9345) anf the NUnitExtension.RowTest (v.1.2.3.0).
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.
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?
It's hard for me to grasp what a rewrite is actually doing. I would like to setup some rules and then be able to throw tests at it and step through it like a debugger.
Hi,
this is something I know I should embrass in my coding projects but, due to lack of knowledge and my legendary lazyness, I do not do.
In fact, when I do them, I feel like overloaded and I finally give up.
What I am looking for is a good book/tutorial on how to really write good tests -i.e useful and covering a large spectrum of the code -.
Regards
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 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();
}
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.
When in PHPUnit test fails, actual and expected values are displayed.
But when the test passes, this information is not displayed.
How to force PHPUnit to always display expected and actual assertion result?
Consider the following code:
[Test]
public void WidgetTest()
{
foreach (Widget widget in widgets)
{
Assert.AreEqual(0, widget.SomeValue);
}
}
If one of the asserts fails, I will get a very unhelpful error message like the one below:
1) Test Failure : WidgetTest.TestSomeValue
Expected: 0
But was: 1
at WidgetTest.TestSomeValue()
So, the question is, how can I get NUnit to display more useful info, such as the name of the widget, or the iteration of the loop, etc? Even a line number would be more helpful, since this is run in automated manner and I'd like to be able to spot the failing assert without debugging into the code.
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
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?
Hello,
I found the discussion on Do you test private method informative.
I have decided, that in some classes, I want to have protected methods, but test them.
Some of these methods are static and short. Because most of the public methods make use of them, I will probably be able to safely remove the tests later. But for starting with a TDD approach and avoid debugging, I really want to test them.
I thought of the following:
Method Object as adviced in an answer seems to be overkill for this.
Start with public methods and when code coverage is given by higher level tests, turn them protected and remove the tests.
Inherit a class with a testable interface making protected methods public
Which is best practice? Is there anything else?
It seems, that JUnit automatically changes protected methods to be public, but I did not have a deeper look at it. PHP does not allow this via reflection.
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
If I forgot to add mappings to a persister object, NHibernate will throw an exception when I'll run the application.
I want to write an integration tests, that test that all mappings are provided to NHibernate.
I have a python program that imports pythoncom (and uses pythoncom.CoCreateInstance from it). I want to create a unittest for the program logic without it importing pythoncom (so I can run the test on Linux as well).
What options are there? Can I do it without modifying the system under test?
What I found so far:
sys.modules["pythoncom"] = "test"
import module_that_imports_pythoncom
My problem with it is if I have:
from pythoncom.something import something
I'll get:
ImportError: No module named something.something
And sys.modules["something.something"] or sys.modules["pythoncom.something.something"] doesn't work.
Any ideas?
We run a project in which we want to solve with test driven development. I thought about some questions that came up when initiating the project. One question was: Who should write the unit-test for a feature? Should the unit-test be written by the feature-implementing programmer? Or should the unit test be written by another programmer, who defines what a method should do and the feature-implementing programmer implements the method until the tests runs?
If I understand the concept of TDD in the right way, the feature-implementing programmer has to write the test by himself, because TDD is procedure with mini-iterations. So it would be too complex to have the tests written by another programmer?
What would you say? Should the tests in TDD be written by the programmer himself or should another programmer write the tests that describes what a method can do?
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... ?