Tag Info

New answers tagged

3

There's a third option: mock the object with the event and use behavior testing to verify the mock's subscriptions at given points. Several mocking frameworks allow for this. public interface INeedToBeMocked { public event EventHandler EventRaised; } NSubstitute var mockedItem = Substitute.For<INeedToBeMocked>(); ...


2

Is there a better way to solve this problem? Yes! C# allows you to override the += and -= syntax. I'm not sure how easy it is to supply in common mocking frameworks like Moq, but it should be trivial to build your own fake object that has hooks into the subscribe and unsubscribe methods of your interface: private Action foo = () => {}; ...


0

I think you are confusing unit tests with property-based testing in your question. Unit tests look at a class as if it was a unit of processing in a signal processing chain, such as an amplifier circuit or a guitar effects rack. I think Kent Beck used exactly this metaphor in his work "Test Driven Development: By Example", but right now I don't have a copy ...


0

Words Of Wisdom for those brave souls who are embracing unit testing After struggling with this question, and googling endless days, I finally came to different conclusion: A good Unit Test should test only one concern, but it can test multiple aspects. In my question, I am asking about multiple aspects, so it is Ok to have three asserts and may/ may not ...


1

This is of course, just my oppinion, but having spent the last few months learning functional programming in fsharp (coming from a C# background) has made me realize a few things. As the OP stated, there are typically 2 types of "unit tests" we see day to day. Tests that cover the in's and out's of a method, which are generally the most valuable, but are ...


2

What is a unit test, really? And is there really such a big dichotomy in play here? We work in a field where reading literally one bit past the end of a buffer can totally crash a program, or cause it to produce a totally inaccurate result, or as evidenced by the recent "HeartBleed" TLS bug, lay a supposedly secure system wide open without producing any ...


0

I don't even agree with the "fail for one reason only" in general. What is more important is that tests are short and reads clearly imo. This is not always achievable though and when a test is complicated a (long) descriptive name and testing fewer things makes more sense.


0

My fuzzy answer is that sometimes having UI unit tests is a good idea, for some parts of the UI. In my experience: Often the people responsible for functional and integration testing are different people than those responsible for unit testing (typically, QA vs. Dev). As such, each may spot different areas (and have different blind spots) as to what ought ...


7

The criteria of "Is it currently being tested by this specific unit test?" If it's not being tested, yeah, stub it, mock it, fake it, set it to a hard known value, whatever. That way you know it's impact on the thing that's actually under test. Even though it's internal to your project and you control the source, it's external to the current thing you're ...


5

I believe it is important to have tests of both types and to use them where appropriate. Like you said, there are two extremes and I honestly do not agree with either one as well. The key is that unit tests have to cover business rules and requirements. If there is a requirement that the system must track a person's age, write "trivial" tests to ensure the ...


3

Here's my take on it: all tests have costs: initial time and effort: think about what to test and how to test it implement the test and make sure it's testing what it's supposed to ongoing maintenance making sure the test is still doing what it's supposed to do as the code evolves naturally running the test execution time analyzing the results We ...


0

I explored the namespaces option in PHP. Namespaces give us the opportunity to add some testing behavior to the DateTime function. Thus, our original objects stay untouched. First, we set up a fake DateTime object in our namespace so that we may, in our tests, manage what time is considered to be "now". Then, in our tests, we can manage this time via the ...


0

It is actually pretty easy. All you need to do is to Extract the logic from Code behind/beside into Presenter class. All ASP.NET specific code should stay in code behind abstracted by View interface, that will be manipulated from Presenter. There is many examples on Model-View-Presenter pattern. Eg. ...


1

I'm going to use Python-like pseudocode based around your test cases to (hopefully) help explain this answer a little, rather than just expositing. But in short: This answer is basically just an example of small, single-function-level dependency injection / dependency inversion, instead of applying the principle to an entire class/object. Right now, it ...


6

This sort of advice makes two key assumptions: You're going to be spending more time looking at some pass/fail summary of all your tests than the assert output. Your tests are only testing a single thing. Now #1 is pretty much guaranteed to be true. #2 is less often going to be true, even if it's good advice. The spirit of the advice is: you should be ...


10

I think it's natural to encounter a divide within unit testing. There are many different opinions on how to do it properly and naturally all other opinions are inherently wrong. There are quite a few articles on DrDobbs recently that explore this very issue to which I link at the end of my answer. The first problem I see with tests is that it's easy to get ...


2

Use Microsoft Fakes - instead of altering your code to suit the tool, the tool alters your code at runtime, injecting a new Time object (that you define in your test) in place of the standard clock. If you're running a dynamic language - then Runkit is just the same type of thing. For example with Fakes: [TestMethod] public void ...


2

When I first learned TDD, I was working in a c# environment. The way I learned to do it is to have a complete IoC environment, which also included an ITimeService, which was responsible for all time services, and could easily be mocked in tests. Nowadays I'm working in ruby, and stubbing time is a lot easier - you simply stub time: describe 'some time ...


7

For my money, holding a dependency on some clock class is the clearest way to go about handling time-dependent testing. In PHP, it may be as simple as a a class with a single function now which returns the current time using time() or new DateTime(). Injecting this dependency allows you to manipulate the time in your tests and use the real time in ...


2

The first thing you need to do is remove the magic numbers from your code. In this case, your "5 minute" magic number. Not only will you inevitably need to change these later when some client demands it, it makes unit testing way better. Who's going to wait 5 minutes for their test to run? Second, if you haven't already, use UTC for actual timestamps. This ...


0

I'm assuming you are writing automated tests using an xUnit framework of some kind. If that is the case, the ideal situation is usually where each function is tested individually. This gives you several advantages: defect localization - when something goes wrong you know exactly where in the code it happened. more control over test input. You can test ...


3

.aspx files, compared to corresponding .aspx.cs code-behind files) are expected to contain minimum programming code, i.e. large chunks of HTML with here and there the calls to variables, eventually with straightforward loops and conditions. This means that you will rarely find unit tests for .aspx files, since there are no complicated algorithms or business ...


1

It is normal to have a build server with a very well control version of the compiler etc on it that builds the software, runs the tests and if the tests pass creates the installer using the same dlls that were tested. There is an additional risk of configuration errors if the software is built in a different way for testing then for shipping.


4

Unit testing can involve a number of different libraries and dependancies than the application that is associated with it. Thinking of an application I recently wrote as a proof of concept (Java) - a simple CRUD app with unit tests against an in memory database. WebApp | Unit Test -------+---------- | JUnit | Mockito Tomcat | Jetty Mysql | ...


0

One thing I learned about dealing with legacy code which I did this for medium and big projects with > 1 million lines of code, it makes sense to use TDD here as well. But it is much harder to get your code there in tests. Normally legacy code bases doen't have any tests in place so fixing a bug and writing a unit test for it is a good starting point to ...


0

TDD shouldn't be used when some alternative approach is more appropriate. The key thing to remember is that the alternative approaches aren't so much manual testing, as things like: Write and review a detailed design document Produce a complete design in a CASE tool, press the 'generate code' button. Create a set of unit tested reusable components, ...


0

Some cases I can think of when one might not want to to TDD are: minor changes to old systems that have no tests. minor changes to old systems that have no test framework. design and development of visual items and effects. tight deadlines and a disinclination to produce quality work.


7

Factors Limiting Industrial Adoption of Test Driven Development, a research paper from 2011, reviewed 9,462 papers on TDD, and included 48 studies as a basis for their research. The paper covers the topic of why TDD may not be used in depth, but for ease of reference, here's a summary: Development time: Development time could be considered a ...


3

I think it all comes down to a simple question: Does it have to work? If it does, then I would say it is best to do TDD, on the majority of cases. To me, the exceptions are very lightweight pieces of code. Weight the effort of manually testing every single procedural branch in the code. If this effort is smaller than that of writing automated tests, then ...


2

You should test sufficiently to provide adequate code coverage. Sufficiently (and adequate) vary on the risk associated with an undetected problem in your code. The cost to fix a problem after development (assuming a classic SDLC) is significantly higher then the cost to fix during development, but the risk may be minimal. So, really that is another way of ...


1

This is a pretty common question to people starting to learn TDD. I don't know if that's your case, but the logic you can follow is the same. First, forget the word "unit" for a moment. Think about how you would approach the development of the same package from ground zero and test-first. You can't start by testing "a class only" or "a method only" because ...


4

Unit testing is the lowest level of testing, but that means only that it is the lowest level you do, not the lowest level you could theoretically do. If you test at the class level, you could test at the method level, using an appropriate test tool to get at private members. But if you test at the method level, you could test at the statement level, using an ...


0

Unit testing is like inductive reasoning. You ensure that the small piece n is well-behaved, and then can trust that as you build up the system, each n + 1 piece is also well-behaved. In your case, I would isolate as many of the 5-6 classes in individual testing to make sure that each one is doing what it should. (That has an extra benefit of speeding up ...


0

The idea behind "a method should test one thing" is so you can immediately see what is causing the problem when the test fails. If you have an assert on three different things then you will have to see what one is going wrong exactly. Another benefit of splitting them up is so you have an overview over what works and what doesn't when an assert fails. If ...


2

As a general rule, if you don't distribute someone else's code you are not obliged by any of its licence terms when you distribute your own. The liability comes at the point where the code is actually merged. Assume that A writes and distributes code for B to use, and that A's program uses code written by C but A does not distribute any of it. Then the ...


0

All good unit test suites do not just test the sunshine cases, but also test to see what happens if something is done that is supposed to be disallowed. You'll have to make an exhaustive list of cases that your unit has to be able to handle. For every one of your casetypes in the snippet you posted, you'll need to think of at least one case that has to ...


16

If someone tells you there is something wrong with: int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable2); AssertEquals("actualValue", 1, actualValue); AssertEquals("actualVariable1", 23, actualVariable1); AssertEquals("actualVariable2", 14, actualVariable2); then they are very likely being overly pedantic, applying a rule blindly ...


-1

An assert is an encapsulation of the test logic: assert foo(x) is y can be written as if foo(x) is not y then throw AssertionError Using assert is encouraged since it's shorter, more readable, and unit testing frameworks may recognize it and treat it specially. Now, you want to have those benefits for assertions that encapsulate a different logic - ...


2

You call this function a number of times with chosen values for variable1. For each input value, you check that each of the output variables and return value match the expected result. You write those as single asserts on each expected value, so that a failure pinpoints the fault. Each input value and set of output values constitutes a single test. The ...


1

My interpretation of that talk is: test components, not classes. test components through their interface ports. It's not stated in the talk, but I think the assumed context for the advice is something like: you are developing a system for users, not, say, a utility library or framework. the goal of testing is to successfully deliver as much as possible ...


2

Your specific example is a case that you usually have to test by checking if a certain method was called, because saving X to data source means communicating with an external dependency, so the behavior you have to test is that the communication is occurring as expected. However, this isn't a bad thing. The boundary interfaces between your application and ...


1

1) are you sure you need to mock your constant? 2) Use Microsoft Fakes, which will happily replace your string with a different one at test-time (an approach that works beautifully when testing more real-world problems, such as mocking the current date/time) (of course, if you use Fakes, you wouldn't have needed to bother with ninject :) )


2

You are talking about performance, which is essentially an Non Functional Requirement. My view is that most of these are for the whole system. A user is never going to say "I want the WidgetListCollection class to return a widget within 20 nanoseconds" -- he might say "I want a list of all products on my screen within 1.5 seconds". The only way to ...


1

How do people/companies handle this type of test? There are many kind of testing, but your interests are unit and functional : unit tests - needs to be very fast, in order to be execute on every change in the code. Their purpose is to test modules. functional tests - they are similar to unit tests, except they do not need to be fast. They are ...


0

The problem its the question itself, you don't need to test all the "methdos" or all the "classes" you need to test all the features of your systems. Its key thinking of terms of features/behaviors instead of thinking in terms of methods and classes. Of course a method its here for providing support for one or more features, at the end all your code its ...


2

There are few types of unit testing: State based. You act and then assert against state of the object. E.g. I make a deposit. I then check to see if balance has increased. Return value based. You act and assert against return value. Interaction based. You verify that your object called another object. This seems to be what you are doing in your example. ...


1

When faced with a philosophical quesion, drop back to the driving requirements. Is your goal to produce reasonably reliable software at a competitive cost? Or is it to produce software of the highest possible reliability almost regardless of cost? Up to a point, the two goals of quality and development speed/cost align: you spend less time writing tests ...


0

Martijn Pieters' solution of splitting tests by class does not always work for me because I split tests by criteria other than what setUp and tearDown they need. So for this kind of situation I typically use a context manager like this: import contextlib @contextlib.contextmanager def temp_dir(): tmpdir = tempfile.mkdtemp(dir="whatever") try: ...


2

In the spirit of unit testing im trying to keep away from using a test file in my test project. In the battle between idealism and pragmatism, sometimes a truce is needed. The main push for not using test files is threefold: Your job isn't to test reading files from disk, it's to test the stuff at hand. Having files tends towards multiple tests ...


1

I'm not sure what "spirit of unit testing" you are talking about. But if you really need to address that spirit ... Have basic tests that use small data sets. You can put string constants in your code for this purpose. Have not-so-basic tests that actually test the things that need to be tested. For these tests, your driver can feel free to call on all the ...



Top 50 recent answers are included