Posts

Showing posts with the label c#

Mock ApiException on Refit

I use Refit to call web api in my code I also like use StatusCode 422 when the web api have to report that there is a logic error in the application and not an exception and use test, to verify the code. So I want write here about this problem, how, with mock and Refit we can test that the application report correctly the 422 status code and a string error(or anything else) WebApi My web api have a class with a response and an error property. public class Response { public string Error { get; set; } public void SetError(string error) { Error = error; } } And the interface of refit public interface IClient { [Post("/Controller/MyMethod")] Task MyMethod([Body]Parameters parameters); } The working code could be something like this public string ApiCaller(IClient client) { try { await client.MyMethod ( new Parameters(...); ); } catch(ApiException ex) when (ex.StatusCode == HttpStatus

Using moq to test class that extends abstract class

Sometimes we've to test a class that extend an anstract class and use other components of the project. For example, we have a ExcelLoader that extend an abstract class Loader, that read an excel file and use data inserted in the file to send mail or send SMS to some users. ExcelLoader It's an important class of our project so it's usefull cover this class with some test, but could be difficult test the class with really instance of the components that send mail and SMS. So we want test only the behavior of ExcelLoader The code public abstract class Loader { public abstract void ImportFile(Stream stream); public abstract IEnumerable<RowFile> GetRows(Stream stream); } public class ExcelLoader : Loader { IMailManager mailManager; ISMSManager smsManager; public ExcelLoader(IMailManager mailManager, ISMSManager smsManager) { this.mailManager = mailManager; this.smsManager = sm

The power of SpecFlow

Writing test could be boring and stakeholders could know how your software should behave. SpecFlow could help you. It's a framework for BDD that uses an extension of Visual Studio that transforms the feature asked by user into code to test. SpecFlow allows you to write the behaviors in your native language and displays the data in a form like Excel table. Install SpecFlow You have to install the extension for Visual Studio in your test project. Install this package, nuget SpecFlow , SpecFlow.Tools.MsBuild.Generation , that will generate the code from our IDE and SpecFlow.xUnit ( if you're using xUnit) that will allow Visual Studio to find the test that specFlow will generate automatically. Background Suppose you want to create tests for a fruit and vegetable warehouse with online purchase. However, be careful to split the sections correctly and it is what I'd like to dwell on. Background is the section where you collect all tha