What's the deal with Deno? We talk with a major contributor to find out. Listen now.

Hot answers tagged

29

This question demonstrates why Test-Driven Development (TDD) is a valuable discipline. If TDD had been strictly followed, the answer would have almost presented itself. To demonstrate that, I copied the tests only (not the 'production code') to a code base, and attempted to figure out what the implementation should be in order to pass each test. Keep in ...


11

There are a number of issues in your code. Naming. Methods should use verb phrases to denote the action they perform and try to be specific. So your DateList method should become something like GetWorkingDates, or just GetDates if kind of dates is obvious in your case. Test naming. Do spend some time on composing a name for your unit test method that ...


9

It's pretty clean. In my oppinion, test parameters should be setup in each test, and not during setup. Setup is for setting up infrastructure bits. You should be able to take advantage of AutoFixture AutoMocking customization to make your tests more resiliant to change (let autofixture create your sut, so adding future dependencies won't break your valid ...


8

Another approach is to use a wrapper for the DirectoryInfo, FileInfo and FileStream. Then your methods can use the wrappers and inject your mocks in the unit tests. Several people have already thought of this and have written the wrappers for you. The one I like is SystemWrapper. Their sample page shows some good examples. Of course, you still have the ...


7

Here be dragons :P This is a conceptual minefield. I have done this exact thing and can relate, you instinctively want to test a lifecycle. a start-to-finish stub implementation..... but don't. the golden rule of unit testing is never test an interface. test an implementation. I'd add a second rule personally, don't test module interaction. If you have ...


5

Initial and General Thoughts Good job! Built fine Tests all passed I like the project structure and naming Source control - I find it easier to handle if packages not there, especially on a slow connection Use nuget package restore I generally use this .gitignore file for this type of project https://github.com/github/gitignore/blob/master/VisualStudio....


5

First of all, your single method is doing multiple things: Get Range by id Copy properties from one instance to another Commit Let's try to separate responsibilities: Range GetRangeById(Repository repo, int id) { return repo.Query<Range>().SingleOrDefault(r=>r.Id == id); } void UpdateRange(Range rangeToUpdate, Range range) { // ...


4

Nice thing in participating/answering in forums like this is that you learn while you answer questions. I haven't heard about SpecsFor framework. Looks a bit tricky, but will definitely have a look later. Ok, back to your question :) About your first question, setting up the mock - you can definitely do that, there are a number of overloaded Returns methods ...


4

I think you are confused about what a mock is actually supposed to be used for. A mock is to create a fake object to pass into a parameter, and is very useful when testing systems that use dependency injection exclusively. Take this for example: public interface IFoo { string SomeMethod(IBar bar); } public interfact IBar { int CalculateSomething(...


3

public abstract class ContextSpecification { protected ContextSpecification() { Context(); BecauseOf(); } protected virtual void BecauseOf() { } protected virtual void Context() { } protected virtual void Cleanup() { } } This class does a few things wrong: The constructor seems to call methods that go beyond a ...


3

Let's review each code segment one by one: public class UserController : Controller { private readonly ILogger<UserController> _logger; private readonly IViewModelService _vmService; public UserController(ILogger<UserController> logger, IViewModelService vmService) { _logger = logger; _vmService = vmService; }...


3

Your first test, CanSetup, will never fail; a .NET constructor can never return null. All of your tests have the same basic setup: create a "manager", create a "workflow", invoke the Assign() method w/ the same arguments. All that changes is how the WF is constructed. Consider: Make the manager part of the fixture (not a local variable) and initialize it ...


2

Strictly to answer the question at hand, you have local variables for the individual contracts already, so you can just re-use them: ohterClassMock.Verify(mock => mock.MethodToTest(It.Is<Contract>(c => contract.Equals(c)))); ohterClassMock.Verify(mock => mock.MethodToTest(It.Is<Contract>(c => contract2.Equals(c)))); This assumes you ...


2

Factory Method vs Constructor In your builder classes you have opted to use factory methods instead of constructors. While this is not necessarily wrong, exposing a factory method generally implies a semantically different operation than constructor invocation. From the Constructor Design guidelines: Consider using a static factory method instead of a ...


2

I think I agree with Jeff. So because of this, perhaps you might want to reconsider the design? Do you really want to make RestClient dependant on WebClient or could we make it dependent on an interface instead and decouple it from that side of things? Perhaps this is overkill? Here's a crack at an alternative for comments: The testing [TestMethod] [...


2

unit tests You can use fakes (stubs vs shims) to mock third-party classes. It is not as lightweight as your regular mocks, but it does the job. exception handling catch (Exception) { return false; } Why don't you do something like Microsoft tends to do often in their framework? You make some internal convenience method IsCriticalException that checks ...


2

MainPageViewModel You provide an interface with a single method: public interface IMainPageViewModel { void LoadGroups(); } Yet, the implementation provides a rich set of public members: public string FileLocation { get; set; } public ObservableCollection<string> Groups { get; set; } public List<Phrase> LoadedPhrases { get; set; } public ...


2

It's fine. Yes, in an ideal world, we'd verify that the id we passed into the PeopleRepository.Get() method is the same one that's getting passed to the client.Get() method, but that's also getting down into testing the internal implementation of the method. What you really care about here is that when the Person isn't found, a specific exception is thrown, ...


2

The tests should be easy to maintain and understand. That is the tool that drives development. Sometimes it may contradict with the widely known rules you mentioned, but it does not mean we should be fanatic about that (as soon as the tests drive the development and work as the safety net). That's totally fine and even more - introducing 'common' ...


1

You could simplify entire test class by extracting part responsible for general configuration. Then you can easili split your test into two, first verifying that your IRestClient is properly called during the process and second that assures tested method returns result provided by this client. For tests that require specific configuration, like throwing ...


1

I am going to re-use an old answer. While the context is slightly different, it is basically the same question. UnitTesting with Mocking and Dependency Injection using Ninject As for the other main question: re: lots of constructor arguments. you are right, this is a code smell. a clear indicator of complexity and shows too much of the guts of the internals....


1

I think, for what it's worth, you have mostly only succeeded in testing your mocks here. Even if you moved these mocks out of the test, I think you'd still only be testing your mock implementation and not much production code. So these tests can pass all day long without reflecting the condition of your production implementations. (If I'm understanding ...


1

Keeping code DRY is a noble goal, even for test code, but it's less important for tests. Our first priority when writing test code is being precise and clear. The tests are the specs and the specs are the tests. It's important that it be immediately clear what the state of the mocked object is. We can expect to duplicate a certain amount of code. Looking ...


1

As a rule, you should prefer to inject dependencies into your objects; this gives you a lot more flexibility going forwards. Example: // these fields can be readonly private readonly Mock<IRepository> _mockRepo; private readonly MockStuffLoggerBuilder _loggerBuilder; private readonly MockAzureQueueManagerBuilder _queueManagerBuilder; public ...


1

Unit Testing means testing single functionality at a time which is there above. More test methods can be added similarly for example when cart is empty, when exception, so on. Moving further you can check whether some property has been set to specific using VerifySet or a function is called or not. The approach is correct, as already said Method names need ...


1

Your test is testing one thing only which is a very good thing. It is better to have many simple tests instead of one massive and it makes bug finding much easier. First of all, I would suggest using more descriptive names for both methods and test. Consider calling Calculate() method differently, i.e. CalculateTotalShippingPrice, so that it indicates what ...


1

I think these two test test two different things. 1st test test correctness of error messages formatting, 2nd - that appropriate method was called. What I don't understand is why do you need expectedErrorCodes variable in tests in the fist place? 200, 201 error codes are just hard coded in your GetErrorList method. So assertion section of the 2nd test may ...


1

Actually you can pass File.Delete as parameter of the function - e.g private void Method( Action<string> deleteFile) And in Unit Test just do following Method((file) => { <VALIDATION> };


Only top voted, non community-wiki answers of a minimum length are eligible